@JSONPropertyIgnore注解org.json序列化java对象时忽略部分属性

这篇博客介绍了如何在Java中使用注解`@JSONPropertyIgnore`来忽略对象的特定属性,例如在将Person对象转换为JSON时,通过忽略`password`属性确保敏感信息不被泄露。示例代码展示了完整和忽略部分属性的JSON输出。
摘要由CSDN通过智能技术生成


import org.json.JSONPropertyIgnore;

public class Person {

    private String name;
    private String about;
    private int birthYear;
    private String password;

    public Person(String name, String about, int birthYear, String password) {
        this.name = name;
        this.about = about;
        this.birthYear = birthYear;
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAbout() {
        return about;
    }

    public void setAbout(String about) {
        this.about = about;
    }

    public int getBirthYear() {
        return birthYear;
    }

    public void setBirthYear(int birthYear) {
        this.birthYear = birthYear;
    }

    @JSONPropertyIgnore
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}
 Person person = DataStore.getInstance().getPerson(name);

        if (person != null) {
//            String json = "{\n";
//            json += "\"name\": " + JSONObject.quote(person.getName()) + ",\n";
//            json += "\"about\": " + JSONObject.quote(person.getAbout()) + ",\n";
//            json += "\"birthYear\": " + person.getBirthYear() + "\n";
//            json += "}";
//            response.getOutputStream().println(json);
            JSONObject object = new JSONObject(person);
            String jsonstring = object.toString();
            System.out.println(jsonstring);
            response.getOutputStream().println(jsonstring);

        } else {
            //That person wasn't found, so return an empty JSON object. We could also return an error.
            response.getOutputStream().println("{}");
        }

java对象完整属性输出:

{"password":"one","birthYear":1816,"name":"Ada","about":"Ada Lovelace was the first programmer."}

使用注解忽略password属性

    @JSONPropertyIgnore
    public String getPassword() {
        return password;
    }

java对象忽略部分属性输出:

{"birthYear":1815,"name":"Ada","about":"Ada Lovelace was the first programmer."}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值