[英]Start Parsing within Nested JSON Object with Jackson
我具有以下JSON結構:
{
"uri": {
"{{firstname}}": "Peter",
"{{lastname}}": "Griffin",
"{{age}}": 42
}
}
我想將其反序列化到我的Bean中:
public class Uri {
private String firstname;
private String lastname;
private int age;
/* getter and setter */
}
但是我收到以下錯誤:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "uri" (class com.abc.Uri), not marked as ignorable (3 known properties: "firstname", "lastname", "age")
所以我想,我需要進入 uri
財產。
有什么辦法可以直接在uri
屬性中開始解析?
更新:
這就是我讀取JSON的方式:
ObjectMapper mapper = new ObjectMapper();
uri = mapper.readValue(new URL("test2.json"), Uri.class);
您的JSON格式應為:
{
"uri": {
"firstname": "Peter",
"lastname": "Griffin",
"age": 42,
}
}
您的方法將不起作用,因為您嘗試一次獲取整個json對象,而不首先獲取特定的節點。
不用使用mapper構造函數加載json,而是以其他方式獲取json。 我將使用URL
和HTTPURLConnection
從網絡獲取json字符串。
擁有json字符串后,請使用以下命令:
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(json);
獲取uri
表示的json節點,如下所示:
JsonNode uriNode = rootNode.get("uri");
然后才發送要解析的節點,如下所示:
Uri uri = objectMapper.treeToValue(uriNode, Uri.class);
Uri uri = objectMapper.readValue(uriNode, Uri.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.