
将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<String, BigDecimal> 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。
@Data
public class Staff {
private String name;
private int age;
private String[] position;
private List<String> skills;
private Map<String, BigDecimal> 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<String> skills;
@JsonIgnore
private Map<String, BigDecimal> 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<String> skills;
private Map<String, BigDecimal> salary;
}
输出:
{
"name" : "mkyong",
"age" : 38,
"skills" : [ "java", "python", "node", "kotlin" ]
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)