基础使用

基础使用

Convert Java to JSON

首先声明有一个简单的 POJO:

// Note: can use getters/setters as well; here we just use public fields directly:
public class MyValue {
  public String name;
  public int age;
// NOTE: if using getters/setters, can keep fields `protected` or `private`
}

然后创建一个 ObjectMapper 实例用于进行转化:

mapper.writeValue(new File("result.json"), myResultObject);
// or:
byte[] jsonBytes = mapper.writeValueAsBytes(myResultObject);
// or:
String jsonString = mapper.writeValueAsString(myResultObject);

案例:Staff

我们可以参考一个实例,将某个 Staff 的信息转化为 JSON 然后写入到文件中,首先来定义实体类:

public class Staff {

	private String name;
	private int age;
	private String position;
	private BigDecimal salary;
	private List<String> skills;

	//getters and setters

然后具体的将 Java 实体类转化为 JSON 的语句为:

// 构建测试对象
private Staff createDummyObject() {

    Staff staff = new Staff();

    staff.setName("test");
    staff.setAge(33);
    staff.setPosition("Developer");
    staff.setSalary(new BigDecimal("7500"));

    List<String> skills = new ArrayList<>();
    skills.add("java");
    skills.add("python");

    staff.setSkills(skills);

    return staff;
}

ObjectMapper mapper = new ObjectMapper();

Staff staff = createDummyObject();

try {
    // Convert object to JSON string and save into a file directly
    mapper.writeValue(new File("staff.json"), staff);

    // Convert object to JSON string
    String jsonInString = mapper.writeValueAsString(staff);
    System.out.println(jsonInString);

    // Convert object to JSON string and pretty print
    jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);
    System.out.println(jsonInString);

} catch (JsonGenerationException e) {
    e.printStackTrace();
} catch (JsonMappingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

最终的输出为:

{
  "name": "test",
  "age": 33,
  "position": "Developer",
  "salary": 7500,
  "skills": ["java", "python"]
}

将 JSON 转化为 Java

将 JSON 转化为 Java 的实体类同样需要用到 ObjectMapper 对象:

ObjectMapper mapper = new ObjectMapper(); // create once, reuse

MyValue value = mapper.readValue(new File("data.json"), MyValue.class);
// or:
value = mapper.readValue(new URL("http://some.com/api/entry.json"), MyValue.class);
// or:
value = mapper.readValue("{\"name\":\"Bob\", \"age\":13}", MyValue.class);

而如果我们要将 JSON 转化为 Java 中的 List 或者 Map 的话,可以采用如下方式:

// 将某个 JSON 转化为数组类型
MyClass[] myObjects = mapper.readValue(json, MyClass[].class);

// 将某个 JSON 转化为 List
String json = "[{\"name\":\"test\"}, {\"name\":\"laplap\"}]";
List<Staff> list = mapper.readValue(json, new TypeReference<List<Staff>>(){});

// 将某个 JSON 转化为 Map
String json = "{\"name\":\"test\", \"age\":33}";
Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String,Object>>(){});

案例:Staff

ObjectMapper mapper = new ObjectMapper();

try {

    // Convert JSON string from file to Object
    Staff staff = mapper.readValue(new File("D:\\staff.json"), Staff.class);
    System.out.println(staff);

    // Convert JSON string to Object
    String jsonInString = "{\"name\":\"test\",\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
    Staff staff1 = mapper.readValue(jsonInString, Staff.class);
    System.out.println(staff1);

    // Pretty print
    String prettyStaff1 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff1);
    System.out.println(prettyStaff1);

} catch (JsonGenerationException e) {
    e.printStackTrace();
} catch (JsonMappingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

最终的输出为:

Staff [name=test, age=33, position=Developer, salary=7500, skills=[java, python]]

Staff [name=test, age=0, position=null, salary=7500, skills=[java, python]]

{
  "name" : "test",
  "age" : 0,
  "position" : null,
  "salary" : 7500,
  "skills" : [ "java", "python" ]
}
上一页
下一页