How can I serialize this JSON using Jackson annotations?

I have the following JSON:

{ fields : { "foo" : "foovalue", "bar" : "barvalue" } } 

I wrote pojo as follows:

 public class MyPojo { @JsonProperty("fields") private List<Field> fields; static class Field { @JsonProperty("foo") private String foo; @JsonProperty("bar") private String bar; //Getters and setters for those 2 } 

This fails because my json field fields is a hashmap, not a list.
My question is: is there any β€œmagic” annotation that can cause Jackson to recognize map keys as pojo property names and assign map values ​​to pojo property values?

PS: I really don't want my field objects to be ...

 private Map<String, String> fields; 

... because in my real json I have complex objects in map values, not just strings ...

Thanks; -)

Philip

+6
java json jackson serialization
source share
1 answer

Well, for this JSON, you just slightly modify your example, for example:

 public class MyPojo { public Fields fields; } public class Fields { public String foo; public String bar; } 

since the structure of objects must be consistent with the structure of JSON. Of course, you can use setters and getters instead of open fields (and even constructors instead of setters or fields), this is just the simplest example.

Your original class will generate / consume JSON more:

 { "fields" : [ { "foo" : "foovalue", "bar" : "barvalue" } ] } 

because lists are mapped to JSON arrays.

+12
source share

All Articles