【发布时间】:2017-03-10 17:49:21
【问题描述】:
我正在尝试使用 Jackson 2.8 反序列化这个 JSON 对象作为改造响应的一部分。这是我从服务器获得的 JSON 响应。
{
"id":"8938209912"
"version":"1.1"
"cars":{
"mercedes":[
{
"property":"color"
},
{
"property":"price"
},
{
"property":"location"
}
],
"tesla":[
{
"property":"environment"
}
]
}
}
根据查询,上面的cars 可能返回一个或多个模型。我不能为每个模型创建一个类,因为它们是任意创建/删除的。对于汽车的每个型号(比如tesla),可能有一个或多个property 键值对。
我是Jackson 的新手。我一直在看几个例子,看起来自定义@JsonDeserialize 是最好的方法。所以,我像这样创建了Root 类和Cars 类:
// In file Root.java
public class Root {
@JsonProperty("id")
private String id = null;
@JsonProperty("version")
private String version = null;
@JsonProperty("cars")
private Cars cars = null;
}
// In file Cars.java
public class Cars {
public Cars(){}
@JsonDeserialize(using = CarDeserializer.class)
private Map<String, List<Property>> properties;
public Map<String, List<Property>> getProperties() {
return properties;
}
public void setProperties(Map<String, List<Property>> properties) {
this.properties = properties;
}
}
// Property.java
public class Property {
@JsonProperty("property")
private String property;
}
我的反序列化器在下面。但是,即使调用了空构造函数,解析方法本身也没有被调用!
// CarDeserializer.class
public class RelationshipDeserializer extends StdDeserializer<Map<String, List<Action>>>{
protected RelationshipDeserializer(){
super(Class.class);
}
@Override
public Map<String, List<Action>> deserialize(JsonParser parser, DeserializationContext ctx)
throws IOException, JsonProcessingException
{
// This method never gets invoked.
}
}
我的问题:
- 首先这是正确的方法吗?
- 为什么你认为执行永远不会到达
deserialize()? (我检查了,cars对象存在于 JSON 中。 - 是否有更好的方法来使用
Jackson解析此 JSON?
【问题讨论】:
标签: java json jackson deserialization