杰克逊动态 Json 映射与类自动



我的json对象是动态的,可能会有10-15种动态json响应,我会得到,

EX: {"a": "B"}, {"a": [a, c, d]}, {a:b, d: []}, {a: []}, {a: [], b:[]} 
these are possible types i have define.
//Before writing the below line, I have to identify the response belongs 
to the correct Class Type and Convert the response into the corosponding Java Class. 
A aResponse = mapper.convertValue(jsonResponse(), A.class );

根据我上面的代码,响应始终考虑采用 A.class 并将抛出异常。

如何识别响应属于特定类,并对其进行转换?

您可以为此使用自定义反序列化程序:

public class Test {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
final SimpleModule module = new SimpleModule("configModule",   Version.unknownVersion());
module.addDeserializer(Root.class, new DeSerializer());
mapper.registerModule(module);
Root readValue = mapper.readValue(<json source>);
}
}
class DeSerializer extends StdDeserializer<Root> {
protected DeSerializer() {
super(Root.class);
}
@Override
public Root deserialize(JsonParser p, DeserializationContext ctxt) throws Exception {
// use p.getText() and p.nextToken to navigate through the json, conditionally check the tags and parse them to different objects and then construct Root object
return new Root();
}
}

最新更新