[英]Jackson json arraylist of unknown fields
I have a JSON string like this: 我有一个像这样的JSON字符串:
{
"123": {
"hi": {
"name": "John",
"phone": "12345"
}
},
"124": {
"hi": {
"name": "James",
"phone": "12345"
}
},
"125": {
"hi": {
"name": "Leo",
"phone": "12347"
}
}
}
The JSON is ordered externally: 123, 124, 125
I just want to get the value of the last field ("125" : {...} ) but I don't know its name, is auto-generated. JSON从外部进行排序:
123, 124, 125
我只想获取最后一个字段的值(“ 125”: {...} ),但我不知道它的名称是自动生成的。 What's the best way? 最好的方法是什么?
I'm trying mapping to an arrayList
of JsonNodes
, but I don't find the right way. 我正在尝试映射到
arrayList
的JsonNodes
,但是找不到正确的方法。
You can also do it using @JsonAnySetter
annotation. 您也可以使用
@JsonAnySetter
批注进行此操作。 Please, see below example. 请参见下面的示例。 POJO class:
POJO类:
class Node {
private Integer key = Integer.MIN_VALUE;
private JsonNode value;
@JsonAnySetter
public void set(String newKey, JsonNode newValue) {
if (Integer.valueOf(newKey) > key) {
value = newValue;
}
}
public JsonNode getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}
Example usage: 用法示例:
ObjectMapper mapper = new ObjectMapper();
Node node = mapper.readValue(json), Node.class);
System.out.println(node);
Prints: 打印:
{"hi":{"name":"Leo","phone":"12347"}}
I did it putting the JSON string in a JsonNode, data and mapping to a NavigableMap. 我将JSON字符串放入JsonNode,数据并映射到NavigableMap。
NavigableMap<String, JsonNode> updates = mapper.readValue(data.traverse(), new TypeReference<TreeMap<String, JsonNode>>() {});
Entry<String, JsonNode> lastEntry = updates.lastEntry();
String lastUpdate = lastEntry.getValue().toString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.