如何使用 Java 中的 @JsonCreator 注解来反序列化 JSON 字符串?


 @JsonProperty 注解可用于指示 JSON 中的属性名称。此注解可用于构造函数 工厂方法@JsonCreator注解在不可使用@JsonSetter注解的情况下非常有用。例如,不可变对象没有 setter 方法,因此需要将它们的初始值注入到构造函数中。

@JsonProperty - 构造函数

示例

import com.fasterxml.jackson.annotation.*;
import java.io.IOException;
import com.fasterxml.jackson.databind.*;
public class JsonCreatorTest1 {
   public static void main(String[] args) throws IOException {
      ObjectMapper om = new ObjectMapper();
      String jsonString = "{\"id\":\"101\", \"fullname\":\"Ravi Chandra\", \"location\":\"Pune\"}";
      System.out.println("JSON: " + jsonString);
      Customer customer = om.readValue(jsonString, Customer.class);
      System.out.println(customer);
   }
}
// Customer class
class Customer {
   private String id;
   private String name;
   private String address;
   public Customer() {
   }
   @JsonCreator
   public Customer(
      @JsonProperty("id") String id,
      @JsonProperty("fullname") String name,  
      @JsonProperty("location") String address) {
      this.id = id;
      this.name = name;
      this.address = address;
   }
   @Override
   public String toString() {
      return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
   }
}

输出

JSON: {"id":"101", "fullname":"Ravi Chandra", "location":"Pune"}
Customer [id=101, name=Ravi Chandra, address=Pune]


@JsonCreator - 工厂方法

示例

import com.fasterxml.jackson.annotation.*;
import java.io.IOException;
import com.fasterxml.jackson.databind.*;
public class JsonCreatorTest2 {
   public static void main(String[] args) throws IOException {
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = "{\"id\":\"102\", \"fullname\":\"Raja Ramesh\",          \"location\":\"Hyderabad\"}";
      System.out.println("JSON: " + jsonString);
      Customer customer = mapper.readValue(jsonString, Customer.class);
      System.out.println(customer);
   }
}
// Customer class
class Customer {
   private String id;
   private String name;
   private String address;
   public Customer() {
   }
   @JsonCreator
   public static Customer createCustomer(
      @JsonProperty("id") String id,
      @JsonProperty("fullname") String name,
   @JsonProperty("location") String address) {
      Customer customer = new Customer();
      customer.id = id;
      customer.name = name;
      customer.address = address;
      return customer;
   }
   @Override
   public String toString() {
         return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
   }
}

输出

JSON: {"id":"101", "fullname":"Raja Ramesh", "location":"Hyderabad"}
Customer [id=102, name=Raja Ramesh, address=Hyderabad]

更新于: 17-2-2020

866 次浏览

开启你的 职业

完成课程即可获得认证

开始吧
广告
© . All rights reserved.