[英]What is the cleanest way to unwrap nested JSON values with Jackson in Java?
I have a JSON which looks like this (number of fields heavily reduced for the sake of example):我有一个 JSON 看起来像这样(例如,字段数量大大减少):
{
"content": {
"id": {"content": "1"},
"param1": {"content": "A"},
"param2": {"content": "55"}
}
}
Keep in mind, that I don't have control over it, I can't change it, that is what I get from API.请记住,我无法控制它,我无法更改它,这就是我从 API 得到的。
I've created a POJO class for this looking like that:我为此创建了一个 POJO class,如下所示:
public class PojoClass {
private String id;
private String param1;
private String param2;
// getters and setters
}
Then I parse JSON with Jackson (I have to use it, please don't suggest GSON or else):然后我用 Jackson 解析 JSON (我必须使用它,请不要建议 GSON 或其他):
ObjectMapper om = new ObjectMapper();
JsonNode jsonNode = om.readTree(json).get("content");
PojoClass table = om.readValue(jsonNode.toString(), PojoClass.class);
And this doesn't work, because of id, param1 and param2 having JSON in them, not straight values.这不起作用,因为 id、param1 和 param2 在其中包含 JSON,而不是直接值。 The code works fine with JSON like this:
该代码适用于 JSON ,如下所示:
{
"content": {
"id": "1",
"param1": "A",
"param2": "55"
}
}
But unfortunately the values I need are stored under "content" fields.但不幸的是,我需要的值存储在“内容”字段下。
What is the cleanest way to resolve this?解决这个问题的最干净的方法是什么?
I understand that I can hardcode this and extract all values into variables one by one in constructor or something, but there are a lot of them, not just 3 like in this example and obviously this is not the correct way to do it.我知道我可以对此进行硬编码并将所有值一个一个地提取到构造函数或其他东西中的变量中,但是它们有很多,而不仅仅是本示例中的 3 个,显然这不是正确的方法。
You can modify the JsonNode
elements like "id": {"content": "1"}
to {"id": "1"}
inside your json string accessing them as ObjectNode
elements with an iterator and after deserialize the new json obtained {"id":"1","param1":"A","param2":"55"}
like below:您可以在
JsonNode
元素(如"id": {"content": "1"}
修改为{"id": "1"}
使用迭代器将它们作为ObjectNode
元素访问,然后反序列化获得的新 json {"id":"1","param1":"A","param2":"55"}
如下所示:
String content = "content";
ObjectMapper om = new ObjectMapper();
JsonNode root = om.readTree(json).get(content);
Iterator<String> it = root.fieldNames();
while (it.hasNext()) {
String fieldName = it.next();
((ObjectNode)root).set(fieldName, root.get(fieldName).get(content));
}
PojoClass table = om.readValue(root.toString(), PojoClass.class);
System.out.println(table); //it will print PojoClass{id=1, param1=A, param2=55}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.