![](/img/trans.png)
[英]Can't serialize with Jackson Json class fields if it extends ArrayList
[英]Jackson json arraylist of unknown fields
我有一個像這樣的JSON字符串:
{
"123": {
"hi": {
"name": "John",
"phone": "12345"
}
},
"124": {
"hi": {
"name": "James",
"phone": "12345"
}
},
"125": {
"hi": {
"name": "Leo",
"phone": "12347"
}
}
}
JSON從外部進行排序: 123, 124, 125
我只想獲取最后一個字段的值(“ 125”: {...} ),但我不知道它的名稱是自動生成的。 最好的方法是什么?
我正在嘗試映射到arrayList
的JsonNodes
,但是找不到正確的方法。
您也可以使用@JsonAnySetter
批注進行此操作。 請參見下面的示例。 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);
}
}
用法示例:
ObjectMapper mapper = new ObjectMapper();
Node node = mapper.readValue(json), Node.class);
System.out.println(node);
打印:
{"hi":{"name":"Leo","phone":"12347"}}
我將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.