简体   繁体   English

Jackson:在对象的不同属性中反序列化JSON-Array

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

I need to decode the following JSON-Structure: 我需要解码以下JSON结构:

{
  "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. 在JSON中,类别数组的第一个条目始终是枚举Category1的值,第二个条目始终是枚举Category2的值,而第三个条目始终是枚举Category3的值。

How can I deserialize this JSON into my class structure using Jackson? 如何使用Jackson将此JSON反序列化为类结构?

You can create your custom deserializer by extending the JsonDeserializer<T> class. 您可以通过扩展JsonDeserializer<T>类来创建自定义解串器。

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注释MyClass

@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. 不相关,但是作为一种好习惯,请将您所有的字段都设为私有,然后公开公共的setter和getter以便控制类的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM