簡體   English   中英

使用Jackson開始在嵌套JSON對象中進行解析

[英]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。 我將使用URLHTTPURLConnection從網絡獲取json字符串。

擁有json字符串后,請使用以下命令:

 ObjectMapper objectMapper = new ObjectMapper();
 JsonNode rootNode = objectMapper.readTree(json);

獲取uri表示的json節點,如下所示:

JsonNode uriNode = rootNode.get("uri");

然后才發送要解析的節點,如下所示:

傑克遜2.4

Uri uri = objectMapper.treeToValue(uriNode, Uri.class);

在Jackson 2.4之前

Uri uri = objectMapper.readValue(uriNode, Uri.class);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM