java - 杰克逊动态 Json 与 Class 自动映射
问题描述
我的 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();
}
}
推荐阅读
- markdown - 在 Next.js 中使用 PrismJS 并在 markdown 中突出显示代码
- python - 用于 Postgres 的 Python 中 jsonb 数组的正确格式是什么?
- javascript - 如何声明一个函数,该函数将接受一个带参数的函数,而其参数中没有参数?
- visual-studio-code - 如何让不同的快捷方式在vscode中打开不同的工作区
- python - DeepCom 通过谷歌云训练模型(seq2 seq 模型):../config/default.yaml 错误
- javascript - 验证是否在 php 上输入了电子邮件
- python - 为复杂的数学表达式绘制二叉树
- javascript - 如何访问这些嵌套数据?
- python - 用python包解析国际地址
- xml - 带有导入 XML 的 Google 表格 - 从该网站获取名称数据