Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot instantiate value of type java.util.LinkedHashMap from String value ('{'); no single-String constructor/factory method

I have the following 2 classes:

@JsonIgnoreProperties(ignoreUnknown = true)
public class ChangesJSON {

    @JsonProperty("changes")
    List<ChangeJSON> changes;

    @JsonProperty("more")
    Boolean more;
}

public class ChangeJSON {

    @JsonProperty("epoch")
    Long epoch;

    @JsonProperty("payload")
    Map<String, Object> payload;
}

When I try to deserialize using this test:

String test = "{\"changes\":[{\"epoch\":1441556306522,\"payload\":\"{\"to\":1}\"},{\"epoch\":1441555481524,\"payload\":\"{\"to\":-1}\"}],\"more\":false}";

@Test
public void myTest() {
    ObjectMapper mapper = new ObjectMapper();
    ChangesJSON result = null;
    try {
        result = mapper.readValue(test, ChangesJSON.class);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    assertNotNull(result);
}

I get the following exception:

com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type java.util.LinkedHashMap from String value ('{'); no single-String constructor/factory method at [Source: {"changes":[{"epoch":1441556306522,"payload":"{"to":1}"},{"epoch":1441555481524,"payload":"{"to":-1}"}],"more":false}; line: 1, column: 35] (through reference chain: demo.ChangesJSON["changes"]->java.util.ArrayList[0]->demo.ChangeJSON["payload"])

It seems that there is an issue with the map but I thought Jackson should be able to handle maps. I get the same issue also when I change the map to Map. But I do need to support all sorts of classes as the values of the map.

like image 277
checklist Avatar asked Mar 14 '23 20:03

checklist


2 Answers

You have quotes around the payload object. Try changing this part:

\"payload\":\"{\"to\":1}\"

into this:

\"payload\":{\"to\":1}
like image 178
Petter Avatar answered Apr 27 '23 06:04

Petter


I think it's the JSON itself that has a problem. It unescapes to:

{"changes":[{"epoch":1441556306522,"payload":"{"to":1}"},{"epoch":1441555481524,"payload":"{"to":-1}"}],"more":false}

It should probably be something like:

{"changes":[{"epoch":1441556306522,"payload":{"to":1}},{"epoch":1441555481524,"payload":{"to":-1}}],"more":false}

So:

String test = "{\"changes\":[{\"epoch\":1441556306522,\"payload\":{\"to\":1}},{\"epoch\":1441555481524,\"payload\":{\"to\":-1}}],\"more\":false}";
like image 39
mprivat Avatar answered Apr 27 '23 07:04

mprivat