如何有条件地将 JSON 字符串反序列化为 POJO 字段?
我收到一个像这样的 JSON 字符串:
{
"status": "we stuck",
"data" : "someData"
}
但“someData”可以只是“桥下”的字符串,也可以是类似“['bridge 5', 'Mandela bridge']”或“[{'incident 1' : '['bridge 1' , 'bridge 2]'},{'incident 2' : ['bridge 99', 'what ever else']}]"
如果“数据”是一个数组,我想按原样返回 json 字符串,然后我将映射到处理该数组的不同类型
我有一个java类:
class Response {
String status;
String data;
}
其他类型的数据为
ArrayList<SomeOtherType> data;
这是我目前的情况
ObjectMapper mapper = new ObjectMapper();
Response rspns = mapper.readValue(<theJSONStrHere>, Response.class);
当数据是一个数组时失败,给我消息
can not deserialize instance of java.lang.String out of START_ARRAY token
我不知道从这里去哪里。
最佳答案
您可以像澳大利亚人所说的那样使用自定义反序列化器,也可以只修改您的工作解决方案。
class Response {
String status;
String data;
}
class Other {
String status;
ArrayList<SomeOtherType> data;
}
ObjectMapper mapper = new ObjectMapper();
Other rspns = mapper.readValue(<theJSONStrHere>, Other.class);
这会将 JSON 字符串解析为带有 ArrayList 的 Other
类。
现在轮到你执行 then to use 的决定了
Other rspns = mapper.readValue(<theJSONStrHere>, Other.class);
或何时使用
Responserspns = mapper.readValue(<theJSONStrHere>, Response.class);
注意:以上是一个快速而肮脏的解决方案。它是这样工作的,但我强烈建议使用自定义反序列化器,它处理它是什么以及返回什么的逻辑。 另请记住,为了使其发挥最佳效果,您可以考虑将 POJO 结构构建为多个类,这些类扩展一个基类然后通用。
示例:
class response {
String status;
}
class simpleResponse extends response {
String data;
}
class listResponse extends response {
ArrayList<Type> data;
}
class MyDeserializer extends JSONDeserializer<E extends response> {
public E deserialize...) {
}
}
要获得实际工作示例,请阅读 Jackson
关于java - 如何使用 Jackson 有条件地反序列化为 POJO 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44042854/