Jackson: Deserialize JSON-Array in different attributes of an object

孤街醉人 提交于 2019-12-12 03:36:20

问题


I need to decode the following JSON-Structure:

{
  "id":1
  "categories": [
    value_of_category1,
    value_of_category2,
    value_of_category3
  ]
}

The object I am trying to deserialize into is of the following class:

class MyClass {
  public Integer id;
  public Category1 category1;
  public Category2 category2;
  public Category3 category3;
...
}

public enum Category1{
...
}

public enum Category2{
...
}

public enum Category3{
...
}

In the JSON the first entry of the categories-Array is always a value of the enum Category1, the second entry is always a value of the enum Category2 and the third entry is always a value of the enum Category3.

How can I deserialize this JSON into my class structure using Jackson?


回答1:


You can create your custom deserializer by extending the JsonDeserializer<T> class.

Here is a sample implementation to fit your needs

public class MyClassDeserializer extends JsonDeserializer<MyClass>{

    @Override
    public MyClass deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        int id = (Integer) ((IntNode) node.get("id")).numberValue();

        JsonNode categories = node.get("categories");
        Iterator<JsonNode> iter = categories.elements();

        while(iter.hasNext()){
            //create Category object based on an incrementing counter
        }

        MyClass myClass = //compose myClass from the values deserialized above.

        return myClass;
    }

}

To use it, you just have to annotate MyClass with @JsonDeserialize pointing to your custom deserializer.

@JsonDeserialize(using = MyClassDeserializer.class)
public class MyClass {

    private Integer id;
    private Category1 category1;
    private Category2 category2;
    private Category3 category3;

}

Not related, but as a good practice, make all your fields private then expose public setters and getters in order to control the fields of the class.



来源:https://stackoverflow.com/questions/35399680/jackson-deserialize-json-array-in-different-attributes-of-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!