直接上代码。非常简单的测试类:
package com.sap.argame.util;
public class Person{
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
Java对象转Json字符串:
就两行代码:
import com.fasterxml.jackson.databind.ObjectMapper;
public static String toJson(Object object) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
}
Json字符串转Java对象:
public static T fromJson(String json, Class clazz) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(json, clazz);
}
测试代码:
Person jerry = new Person("Jerry