1.添加maven依赖
com.fasterxml.jackson.core
jackson-annotations
${jackson.version}
com.fasterxml.jackson.core
jackson-core
${jackson.version}
com.fasterxml.jackson.core
jackson-databind
${jackson.version}
2.工具类编写
import com.boomsecret.domain.Person;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public final class JacksonUtils {
private JacksonUtils() {}
public final static ObjectMapper MAPPER;
static {
MAPPER = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public static String serialize(Object obj) {
try {
return MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public static Object deserialize(String jsonText, TypeReference type) {
try {
return MAPPER.readValue(jsonText, type);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static T deserialize(String jsonText, Class beanClass) {
try {
return MAPPER.readValue(jsonText, beanClass);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static JsonNode deserialize(String jsonText) {
try {
return MAPPER.readTree(jsonText);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
3.具体使用
public static void main(String[] args) {
Person person = new Person(18, "tom");
String personJson = JacksonUtils.serialize(person);
System.out.println(personJson);
Person newPerson = JacksonUtils.deserialize(personJson, Person.class);
System.out.println(newPerson);
}
4.补充
@JsonIgnore 此注解用于属性上 作用是进行JSON操作时忽略该属性
@JsonFormat 此注解用于属性上 作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")
@JsonProperty 此注解用于属性上 作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty("name")