直接上代码。非常简单的测试类:
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> T fromJson(String json, Class<T> clazz) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(json, clazz);
}
测试代码:
Person jerry = new Person("Jerry", 36);
String json = null;
try {
json = toJson(jerry);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(json);
Person another = null;
try {
another = (Person)fromJson(json, Person.class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Name: " + another.getName() + " age: " + another.getAge());
System.out.println(jerry == another);
最后的jerry和another实例的比较会得到期望的false,这也是通过序列化/反序列化攻击单例模式实现的例子。
要获取更多Jerry的原创文章,请关注公众号"汪子熙":