首页 > Java > java教程 > 正文

如何在Java中忽略JSON对象的多个属性?

王林
发布: 2023-09-18 22:29:02
转载
683 人浏览过

如何在Java中忽略JSON对象的多个属性?

@JsonIgnorePropertiesJackson 注释可用于指定要忽略的类的属性列表字段@JsonIgnoreProperties annotation 可以放置在类声明之前,而不是放置在单个属性或字段之前以进行忽略。

语法

@Target(value={ANNOTATION_TYPE,TYPE,METHOD,CONSTRUCTOR,FIELD})
@Retention(value=RUNTIME)
public @interface JsonIgnoreProperties
登录后复制

示例

import java.io.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
public class JsonIgnorePropertiesTest {
   public static void main(String[] args) throws IOException {
      Customer customer = new Customer("120", "Ravi", "Hyderabad");
      System.out.println(customer);
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writeValueAsString(customer);
      System.out.println("JSON: " + jsonString);
      System.out.println("---------");
      jsonString = "{\"id\":\"130\",\"name\":\"Rahul\", \"address\":\"Mumbai\"}";
      System.out.println("JSON: " + jsonString);
      customer = mapper.readValue(jsonString, Customer.class);
      System.out.println(customer);
   }
}
// Customer class
@JsonIgnoreProperties({"id", "address"}) <strong>
</strong>class Customer {
   private String id;
   private String name;
   private String address;
   public Customer() {
   }
   public Customer(String id, String name, String address) {
      this.id = id;
      this.name = name;
      this.address = address;
   }
   public String getId() {
      return id;
   }
   public String getName() {
      return name;
   }
   public String getAddress() {
      return address;
   }
<strong>   </strong>@Override
   public String toString() {
      return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
   }
}
登录后复制

输出

Customer [id=120, name=Ravi, address=Hyderabad]
JSON: {"name":"Ravi"}
---------
JSON: {"id":"130","name":"Rahul", "address":"Mumbai"}
Customer [id=null, name=Rahul, address=null]
登录后复制

以上是如何在Java中忽略JSON对象的多个属性?的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板