开发者

How can I serialize this JSON using Jackson annotations?

I have the following JSON :

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

I wrote a pojo as follows :

pu开发者_运维技巧blic 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 obviously, because my json field "fields" is a hashmap, and not a list.

My question is : is there any "magic" annotation that can make Jackson recognize the map keys as pojo property names, and assign the map values to the pojo property values ?

P.S.: I really don't want to have my fields object as a...

private Map<String, String> fields;

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

Thanks ;-)

Philippe


Ok, for that JSON, you would just modify your example slightly, like:

public class MyPojo {
  public Fields fields;
}

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

since structure of objects needs to align with structure of JSON. You could use setters and getters instead of public fields of course (and even constructors instead of setters or fields), this is just the simplest example.

Your original class would produce/consume JSON more like:

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

because Lists map to JSON arrays.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜