Home > OS >  (Java, Jackson) How to map a json not having field name to a class with a field of given type
(Java, Jackson) How to map a json not having field name to a class with a field of given type

Time:07-15

I have a json string like this:

{
"a": ["cat", "dog"],
"b" : ["jaguar"],
"c": ["sparrow", "penguin"]
}

and I want to map it to a model as follows:

public class MyClass {
    private Map<String, List<String>> someField;
}

How can I map given JSON to the given class? I am not able to do so because my json is not of the type:

{
"someField" : {
"a": ["cat", "dog"],
"b" : ["jaguar"],
"c": ["sparrow", "penguin"]
   }
}

i.e. it does not contain the field name.

Is there any way other than writing a custom deserializer?

CodePudding user response:

It is possible without much work. Looking at this link, we create our class like this:

@Data
class MyClass {
    private Map<String, List<String>> someField;

    @JsonCreator
    public MyClass(Map<String, List<String>> map) {
        this.someField = map;
    }

}

And then we read the JSON like this:

ObjectMapper mapper = new ObjectMapper();
MyClass readValue = mapper.readValue("{\n"   "\"a\": [\"cat\", \"dog\"],\n"
          "\"b\" : [\"jaguar\"],\n"   "\"c\": [\"sparrow\", \"penguin\"]\n"   "}",
        MyClass.class);
System.out.println(readValue);

and receive an output like this:

MyClass(someField={a=[cat, dog], b=[jaguar], c=[sparrow, penguin]})

The key is @JsonCreator in the custom constructor, which tells Jackson to convert the JSON to the specified type (Map<String, List<String>>) and build an instance from using that type as parameter for the constructor

  • Related