栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Jackson - 注解 @JsonIgnore 和@JsonIgnoreProperties:忽略字段

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Jackson - 注解 @JsonIgnore 和@JsonIgnoreProperties:忽略字段

将java对象转换为json字符串:

public class JacksonExample1 {
    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();
        Staff staff = createStaff();

        try {
            // Java objects to JSON string - pretty-print
            String jsonString
                    = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);
            System.out.println(jsonString);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static Staff createStaff() {

        Staff staff = new Staff();

        staff.setName("mkyong");
        staff.setAge(38);
        staff.setPosition(new String[]{"Founder", "CTO", "Writer"});
        Map salary = new HashMap() {{
            put("2010", new BigDecimal(10000));
            put("2012", new BigDecimal(12000));
            put("2018", new BigDecimal(14000));
        }};
        staff.setSalary(salary);
        staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));

        return staff;
    }
}

默认情况下,Jackson 包括所有字段,甚至是static字段transient。

1. 默认方式
@Data
public class Staff {

    private String name;
    private int age;
    private String[] position;
    private List skills;
    private Map salary;

}

输出:

{
  "name" : "mkyong",
  "age" : 38,
  "position" : [ "Founder", "CTO", "Writer" ],
  "skills" : [ "java", "python", "node", "kotlin" ],
  "salary" : {
    "2018" : 14000,
    "2012" : 12000,
    "2010" : 10000
  }
}
2. @JsonIgnore 忽略字段级别的字段
@Data
public class Staff {

    private String name;
    private int age;
    private String[] position;

    @JsonIgnore
    private List skills;
    
    @JsonIgnore
    private Map salary;
}

输出:

{
  "name" : "mkyong",
  "age" : 38,
  "position" : [ "Founder", "CTO", "Writer" ]
}
3. @JsonIgnoreProperties 忽略类级别的字段
@JsonIgnoreProperties({"salary", "position"})
@Data
public class Staff {

    private String name;
    private int age;
    private String[] position;
    private List skills;
    private Map salary;
    
}

输出:

{
  "name" : "mkyong",
  "age" : 38,
  "skills" : [ "java", "python", "node", "kotlin" ]
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/874031.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号