Jackson:在对象的不同属性中反序列化JSON-Array [英] Jackson: Deserialize JSON-Array in different attributes of an object
问题描述
我需要解码以下JSON结构:
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{
...
}
在JSON中,categories-Array的第一个条目始终是枚举Category1的值,第二个条目始终是枚举Category2的值,第三个条目始终是枚举类别3的值。
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.
如何使用Jackson将此JSON反序列化为我的类结构?
How can I deserialize this JSON into my class structure using Jackson?
推荐答案
您可以通过扩展 JsonDeserializer< T>
class。
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;
}
}
要使用它,你只需拥有它使用 @JsonDeserialize
注释 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;
}
不相关,但作为一个好习惯,让你所有的字段private然后公开公共setter和getter以控制类的字段。
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.
这篇关于Jackson:在对象的不同属性中反序列化JSON-Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!