Java Jackson:用于反序列化内部集合的对象映射器注释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25185545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hymanson: Object Mapper annotations to deserialize a inner collection
提问by tehAnswer
I want to convert the following json into a java object, using as much as possible annotations.
我想将以下 json 转换为 java 对象,尽可能多地使用 annotations。
{"user":{
"id":1,
"diets":[
{"diet":{
"name":"...",
"meals":[]
}
}
]
}
}
I'm getting trouble with the collection diets. I tried to use @JsonProperty
but it doesn't work properly. Is there a special annotation for map inner aggregates?
我在收集饮食方面遇到了麻烦。我尝试使用@JsonProperty
但它不能正常工作。地图内部聚合是否有特殊注释?
Diet.java
饮食.java
@JsonRootName(value = "diet")
public class Diet {
@JsonProperty(value="name")
private String name;
@JsonProperty(value="meals")
private List<Meal> meals;
private User user;
// Rest of the class omitted.
}
User.java
用户.java
@JsonRootName(value = "user")
public class User {
@JsonProperty("id")
private long id;
@JsonProperty("diets")
private List<Diet> diets = new ArrayList<Diet>();
// Rest of the class omitted.
}
Thanks!
谢谢!
采纳答案by Syam S
The diets object in your json is not a List. Its a List of key-value pair with key "diet" and value a diet object. So you have three options here.
json 中的饮食对象不是列表。它是一个键值对列表,带有键“饮食”和值一个饮食对象。所以你在这里有三个选择。
One is to create a wrapper object say DietWrapper and use List of diet wrapper in User like
一种是创建一个包装器对象说 DietWrapper 并在 User 中使用饮食包装器列表
@JsonRootName(value = "user")
class User {
@JsonProperty(value = "id")
private long id;
@JsonProperty(value = "diets")
private List<DietWrapper> diets;
//Getter & Setters
}
class DietWrapper {
@JsonProperty(value = "diet")
Diet diet;
}
Second option is to keep diest as simple list of maps like List>
第二种选择是将 diet 保留为简单的地图列表,例如 List>
@JsonRootName(value = "user")
class User {
@JsonProperty(value = "id")
private long id;
@JsonProperty(value = "diets")
private List<Map<String, Diet>> diets;
//Getter & Setters
}
Third option is to use a custom deserializer which would ignore your diet class.
第三种选择是使用自定义解串器,它会忽略您的饮食类。
@JsonRootName(value = "user")
class User {
@JsonProperty(value = "id")
private long id;
@JsonProperty(value = "diets")
@JsonDeserialize(using = DietDeserializer.class)
private List<Diet> diets;
//Getter & Setters
}
class DietDeserializer extends JsonDeserializer<List<Diet>> {
@Override
public List<Diet> deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonParser);
List<Diet> diets = mapper.convertValue(node.findValues("diet"), new TypeReference<List<Diet>>() {});
return diets;
}
}