我的json对象是动态的,我可能会得到arounf 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并将引发异常。
我如何识别属于特定类的响应并将其转换?
答案 0 :(得分:0)
您可以为此使用自定义反序列化器:
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();
}
}