1. Person.java
package pojo;
public class Person {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2. JSONUtil.java
package util;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JSONUtil {
public static String getJSONString(Object obj){
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.writeValueAsString(obj);
// 格式化打印
// return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static <T> T getObjectFromJSONString(String json,Class<T> clazz){
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.readValue(json, clazz);
} catch (JsonParseException e) {
throw new RuntimeException(e);
} catch (JsonMappingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
3. Main.java 测试类
package test;
import pojo.Person;
import util.JSONUtil;
public class Main {
public static void main(String[] args) throws Exception {
Person person = new Person();
person.setId("001");
person.setName("name");
String str = JSONUtil.getJSONString(person);
Person person2 = JSONUtil.getObjectFromJSONString(str, Person.class);
System.out.println(person2);
}
}