首页 >Java >java教程 >如何在Java中使用Jackson对象模型映射JSON数据?

如何在Java中使用Jackson对象模型映射JSON数据?

WBOY
WBOY转载
2023-09-01 16:33:06668浏览

如何在Java中使用Jackson对象模型映射JSON数据?

ObjectMapper类提供了在 Java 对象和匹配 JSON 结构之间进行转换的功能。我们可以使用树状数据结构来实现将对象模型表示的JSON数据映射到特定的Java对象,该数据结构读取内存中的整个JSON内容并将其存储。第一步,将 JSON 数据读入 JsonNode object ,然后通过调用 ObjectMapper class 的 treeToValue() 方法将其映射到另一个实例。

语法

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();
   }
}

输出

嗯嗯

以上是如何在Java中使用Jackson对象模型映射JSON数据?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除