想要隐藏由 Jackson 映射到 JSON 的对象的某些字段 [英] Want to hide some fields of an object that are being mapped to JSON by Jackson

查看:27
本文介绍了想要隐藏由 Jackson 映射到 JSON 的对象的某些字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 User 类,我想使用 Jackson 将其映射到 JSON.

I have a User class that I want to map to JSON using Jackson.

public class User {
    private String name;
    private int age;
    prviate int securityCode;

    // getters and setters
}

我使用 -

User user = getUserFromDatabase();

ObjectMapper mapper = new ObjectMapper();   
String json =  mapper.writeValueAsString(user);

我不想映射 securityCode 变量.有没有办法配置映射器使其忽略此字段?

I don't want to map the securityCode variable. Is there any way of configuring the mapper so that it ignores this field?

我知道我可以编写自定义数据映射器或使用 Streaming API,但我想知道是否可以通过配置来实现?

I know I can write custom data mappers or use the Streaming API but I would like to know if it possible to do it through configuration?

推荐答案

您有两个选择:

  1. Jackson 致力于字段的 setter-getter.因此,您可以删除要在 JSON 中省略的字段的 getter.(如果你在其他地方不需要 getter.)

  1. Jackson works on setters-getters of fields. So, you can just remove getter of field which you want to omit in JSON. ( If you don't need getter at other place.)

或者,您可以使用 @JsonIgnore Jackson 的注释 在该字段的 getter 方法上,您会在结果 JSON 中看到没有这样的键值对.

Or, you can use the @JsonIgnore annotation of Jackson on getter method of that field and you see there in no such key-value pair in resulted JSON.

@JsonIgnore
public int getSecurityCode(){
   return securityCode;
}

这篇关于想要隐藏由 Jackson 映射到 JSON 的对象的某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆