首頁 >Java >java教程 >如何在Java中使用Jackson物件模型來映射JSON資料?

如何在Java中使用Jackson物件模型來映射JSON資料?

WBOY
WBOY轉載
2023-09-01 16:33:06670瀏覽

如何在Java中使用Jackson物件模型來映射JSON資料?

ObjectMapper 類別提供了在 Java 物件和匹配 JSON 結構之間轉換的功能。我們可以使用tree-like 資料結構來實現將Object Model 表示的JSON 資料映射到特定的Java 對象,該資料結構讀取記憶體中的整個JSON 內容並將其存儲。第一步,將 JSON 資料讀入 JsonNode object ,然後透過呼叫 ObjectMapper # 的 treeToValue() 方法將其對應到另一個實例##class.

語法

public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException

範例

import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
public class JsonTreeModelDemo {
   public static void main(String[] args) throws JsonProcessingException, IOException {
      String jsonString = "{\"id\":\"102\", \"name\":\"Raja Ramesh\", \"address\":[{\"area\":\"Madhapur\", \"city\":\"Hyderabad\"}]}";
      ObjectMapper objectMapper = new ObjectMapper();
      JsonNode jsonNode = objectMapper.readTree(jsonString);
      User user = objectMapper.treeToValue(jsonNode, User.class);
      System.out.println(user);
   }
}
// User class
class User {
   private int id;
   private String name;
   private Address[] address;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public Address[] getAddress() {
      return address;
   }
   public void setAddress(Address[] address) {
      this.address = address;
   }
<strong>   @Override
</strong>   public String toString() {
      StringBuilder sb = new StringBuilder();
      sb.append("{");
      sb.append(id).append(",");
      sb.append(name).append(",");
      for(Address address1 : address) {
         sb.append(address1).append(",");
      }
      sb.append("}");
      return sb.toString();
   }
}
// Address class
class Address {
   private String area;
   private String city;
   public String getArea() {
      return area;
   }
   public void setArea(String area) {
      this.area = area;
   }
   public String getCity() {
      return city;
   }
   public void setCity(String city) {
      this.city = city;
   }
<strong>  </strong> @Override<strong>
</strong>   public String toString() {
      StringBuilder sb = new StringBuilder();
      sb.append("{");
      sb.append(area).append(",");
      sb.append(city);
      sb.append("}");
      return sb.toString();
   }
}

輸出

{102,Raja Ramesh,{Madhapur,Hyderabad},}

以上是如何在Java中使用Jackson物件模型來映射JSON資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除