在序列化的时候,有时被序列化的对象 里面的字段 和get,set方法对应的不一样,但是序列化的时候希望出现”name”:”xxx” 而不是 “studentName”:”xxx” json串。”如下:
class Student{
private String name;
private int age;
public String getStudentName() {
return name;
}
public void setStudentName(String name) {
this.name = name;
}
public int getStudentAge() {
return age;
}
public void setStudentAge(int age) {
this.age = age;
}
}
代码实例:
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
Student stu = new Student();
stu.setStudentName("王者");
stu.setStudentAge(12);
ObjectMapper map = new ObjectMapper();
String json = map.writeValueAsString(stu);
System.out.println(json);
}
输出的结果为:
{“studentName”:”王者”,”studentAge”:12}
如果想得到json 串为{“name”:”王者”,”age”:12}
需要进行如下配置:
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
Student stu = new Student();
stu.setStudentName("王者");
stu.setStudentAge(12);
ObjectMapper map = new ObjectMapper();
map.setVisibility(JsonMethod.SETTER, Visibility.NONE);
map.setVisibility(JsonMethod.GETTER, Visibility.NONE);
map.setVisibility(JsonMethod.FIELD, Visibility.ANY);
String json = map.writeValueAsString(stu);
System.out.println(json);
}
输出结果为:
{“name”:”王者”,”age”:12}