Jackson JSON - Using @JsonIgnore and @JsonIgnoreProperties to ignore properties

 

  

Following example shows how to use @JsonIgnore and @JsonIgnoreProperties annotations to ignore properties.

@JsonIgnore Example

@JsonIgnore can be used on fields or getters or setters to ignore individual properties.

public class Employee {
  private String name;
  private String dept;
  @JsonIgnore
  private String address;
    .............
}
public class ExampleMain {
  public static void main(String[] args) throws IOException {
      Employee employee = new Employee();
      employee.setName("Trish");
      employee.setDept("Admin");
      employee.setAddress("421 Moon Hill");

      //convert to json
      String jsonString = toJson(employee);
      System.out.println(jsonString);
      //convert to object;
      Employee e = toEmployee(jsonString);
      System.out.println(e);

      //address here will be ignore too
      String s = "{\"name\":\"Trish\",\"dept\":\"Admin\", \"address\":\"xyz Street\"}";
      System.out.println("JSON input: "+s);
      Employee e2 = toEmployee(s);
      System.out.println(e2);
  }

  private static Employee toEmployee(String jsonData) throws IOException {
      ObjectMapper om = new ObjectMapper();
      return om.readValue(jsonData, Employee.class);
  }

  private static String toJson(Employee employee) throws IOException {
      ObjectMapper om = new ObjectMapper();
      return om.writeValueAsString(employee);
  }
}
{"name":"Trish","dept":"Admin"}
Employee{name='Trish', dept='Admin', address='null'}
JSON input: {"name":"Trish","dept":"Admin", "address":"xyz Street"}
Employee{name='Trish', dept='Admin', address='null'}

 

@JsonIgnoreProperties Example

This annotation can be used to ignore multiple properties with one declaration:

@JsonIgnoreProperties({"dept", "address"})
public class Employee2 {
  private String name;
  private String dept;
  private String address;
    .............
}
public class ExampleMain2 {
  public static void main(String[] args) throws IOException {
      Employee2 employee = new Employee2();
      employee.setName("Trish");
      employee.setDept("Admin");
      employee.setAddress("421 Moon Hill");

      //convert to json
      String jsonString = toJson(employee);
      System.out.println(jsonString);
      //convert to object;
      Employee2 e = toEmployee(jsonString);
      System.out.println(e);

      //address/dept here will be ignored even they are in the source JSON
      String s = "{\"name\":\"Trish\",\"dept\":\"Admin\", \"address\":\"xyz Street\"}";
      System.out.println("JSON input: "+s);
      Employee2 e2 = toEmployee(s);
      System.out.println(e2);
  }

  private static Employee2 toEmployee(String jsonData) throws IOException {
      ObjectMapper om = new ObjectMapper();
      return om.readValue(jsonData, Employee2.class);
  }

  private static String toJson(Employee2 employee) throws IOException {
      ObjectMapper om = new ObjectMapper();
      return om.writeValueAsString(employee);
  }
}
{"name":"Trish"}
Employee{name='Trish', dept='null', address='null'}
JSON input: {"name":"Trish","dept":"Admin", "address":"xyz Street"}
Employee{name='Trish', dept='null', address='null'}

Ignoring Unknown Properties

@JsonIgnoreProperties#ignoreUnknown can be used to ignore a JSON property if is not defined in the POJO:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Employee3 {
  private String name;
  private String dept;
  private String address;
    .............
}
public class ExampleMain3 {
  public static void main(String[] args) throws IOException {
      String jsonString = "{\"name\":\"Trish\",\"phone\":\"111-111-1111\"}";
      System.out.println(jsonString);
      //convert to object;
      Employee3 e = toEmployee(jsonString);
      System.out.println(e);
  }

  private static Employee3 toEmployee(String jsonData) throws IOException {
      ObjectMapper om = new ObjectMapper();
      return om.readValue(jsonData, Employee3.class);
  }
}
{"name":"Trish","phone":"111-111-1111"}
Employee{name='Trish', dept='null', address='null'}

Without ignoreUnknown = true, we will have following exception:

Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "phone" (class com.logicbig.example.Employee3), not marked as ignorable (3 known properties: "name", "address", "dept"])
 at [Source: (String)"{"name":"Trish","phone":"111-111-1111"}"; line: 1, column: 26] (through reference chain: com.logicbig.example.Employee3["phone"])
	at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:60)
	at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:822)
	at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1152)
	at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1567)
	at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1545)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:293)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4001)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2992)
	at com.logicbig.example.ExampleMain3.toEmployee(ExampleMain3.java:18)
	at com.logicbig.example.ExampleMain3.main(ExampleMain3.java:12)
### Java `@JsonIgnore` 注解的使用 #### 基本概念 `@JsonIgnore` 是 Jackson 库中的一个重要注解,用于指定某些字段或方法不应被序列化为 JSON 输出或将 JSON 输入反序列化到这些属性中。当应用于 getter 方法、setter 方法或是直接作用于字段时,该注解能够阻止特定的数据成员参与自动化的 JSON 转换过程。 对于那些不希望暴露给外部系统的敏感信息或者是内部使用的辅助数据结构来说非常有用[^1]。 #### 使用实例 下面通过几个例子来展示如何正确地运用此注解: ##### 场景一:忽略单个字段 假设有一个简单的 User 类,其中包含了一些基本信息以及密码字段 password。为了安全起见,在将对象转成 JSON 字符串的时候我们不想让 password 出现在最终的结果里,则可以在定义这个类的时候加上相应的注解。 ```java public class User { private String username; @JsonIgnore private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } // This will be ignored during serialization. } ``` 在这个案例中,即使调用了 `getPassword()` 方法获取到了值也不会出现在生成的 JSON 文档里面[^2]. ##### 场景二:处理混淆后的代码 考虑到项目可能进行了字节码级别的优化或者保护措施(如前所述),这可能导致原本加在私有域上的注解变得不再有效。为了避免这种情况发生,建议把像 `@JsonIgnore`, `@JSONField` 这样的标记放置到对应的 setter/getter 上面而不是直接放在属性声明处。 ```java public class SecureUser { private transient String secretToken; // Using 'transient' keyword as an alternative way to ignore. public String getSecretToken() { return secretToken; } @JsonIgnore public void setSecretToken(String secretToken) { this.secretToken = secretToken; } } ``` 这里不仅展示了如何利用 `@JsonIgnore` 来控制序列化行为,同时也提到了另一种方式——即使用 Java 的内置关键字 `transient`. 它同样能达到不让某个变量参与到默认序列化进程的效果[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值