概述
将对象转换为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;
}
}
1. 默认方式
@Data
public class Staff {
private String name;
private int age;
private String[] position; // Array
private List<String> skills; // List
private Map<String, BigDecimal> salary; // Map
}
输出:
{
"name" : "mkyong",
"age" : 38,
"position" : [ "Founder", "CTO", "Writer" ],
"skills" : [ "java", "python", "node", "kotlin" ],
"salary" : {
"2018" : 14000,
"2012" : 12000,
"2010" : 10000
}
}
2. 更改属性名称@JsonProperty
从 json 字符串到对象:
@Data
public class Staff {
@JsonProperty("custom_name")
private String name;
private int age;
private String[] position; // Array
private List<String> skills; // List
private Map<String, BigDecimal> salary; // Map
}
输出:
{
"age" : 38,
"position" : [ "Founder", "CTO", "Writer" ],
"skills" : [ "java", "python", "node", "kotlin" ],
"salary" : {
"2018" : 14000,
"2012" : 12000,
"2010" : 10000
},
"custom_name" : "mkyong"
}
3. 更改属性名称@JsonProperty
从对象到 json 字符串:
@Data
public class Staff {
@JsonProperty("custom_name")
private String name;
private int age;
private String[] position;
private List<String> skills;
private Map<String, BigDecimal> salary;
}
public class JacksonExample2 {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
// JSON string to Java object
String jsonInString = "{n" +
" "age" : 38,n" +
" "position" : [ "Founder", "CTO", "Writer" ],n" +
" "skills" : [ "java", "python", "node", "kotlin" ],n" +
" "salary" : {n" +
" "2018" : 14000,n" +
" "2012" : 12000,n" +
" "2010" : 10000n" +
" },n" +
" "custom_name" : "mkyong"n" +
"}";
Staff staff2 = mapper.readValue(jsonInString, Staff.class);
System.out.println(staff2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出:
Staff(name=mkyong, age=38, position=[Founder, CTO, Writer], skills=[java, python, node, kotlin], salary={2018=14000, 2012=12000, 2010=10000})
最后
以上就是单薄小土豆为你收集整理的Jackson - 注解 @JsonProperty:字段命名的全部内容,希望文章能够帮你解决Jackson - 注解 @JsonProperty:字段命名所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复