1 对象转换为json
ObjectMapper mapper = new ObjectMapper();
Staff obj = new Staff();
mapper.writeValue(new File("c:\\file.json"), obj);
String jsonInString = mapper.writeValueAsString(obj);
2 json转换为object
ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mkyong'}";
//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
//JSON from URL to Object
Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);
//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);
3 格式化输出
// Convert object to JSON string and pretty print
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);
System.out.println(jsonInString);
{
"name" : "mkyong",
"age" : 33,
"position" : "Developer",
"salary" : 7500,
"skills" : [ "java", "python" ]
}
4 使用@JsonView, 控制哪些字段输出
先定义view
public class Views {
public static class Normal{};
public static class Manager extends Normal{};
}
对于normal的,是看不到薪酬,如果经理,则看到
public class Staff {
@JsonView(Views.Normal.class)
private String name;
@JsonView(Views.Normal.class)
private int age;
@JsonView(Views.Normal.class)
private String position;
@JsonView(Views.Manager.class)
private BigDecimal salary;
@JsonView(Views.Normal.class)
private List<String> skills;
则:
// Salary will be hidden
System.out.println("Normal View");
String normalView = mapper.writerWithView(Views.Normal.class).writeValueAsString(staff);
System.out.println(normalView);
String jsonInString = "{\"name\":\"mkyong\",\"age\":33,\"position\":\"Developer\",\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
Staff normalStaff = mapper.readerWithView(Views.Normal.class).forType(Staff.class).readValue(jsonInString);
System.out.println(normalStaff);
// Display everything
System.out.println("\nManager View");
String managerView = mapper.writerWithView(Views.Manager.class).writeValueAsString(staff);
System.out.println(managerView);
Staff managerStaff = mapper.readerWithView(Views.Manager.class).forType(Staff.class).readValue(jsonInString);
System.out.println(managerStaff);
输出:
Normal View
{"name":"mkyong","age":33,"position":"Developer","skills":["java","python"]}
Staff [name=mkyong, age=33, position=Developer, salary=null, skills=[java, python]]
Manager View
{"name":"mkyong","age":33,"position":"Developer","salary":7500,"skills":["java","python"]}
Staff [name=mkyong, age=33, position=Developer, salary=7500, skills=[java, python]]
5 常见问题
json转变为数组
String json = "[{\"name\":\"mkyong\"}, {\"name\":\"laplap\"}]";
List<Staff> list = mapper.readValue(json, new TypeReference<List<Staff>>(){});
把json转变为map
String json = "{\"name\":\"mkyong\", \"age\":33}";
Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String,Object>>(){});