前提条件: JSON 的开源框架选择Jackson
直接上货:ObjectMapper
- ObjectMapper提供了读写JSON的功能
- 支持pojo和流式
- 构造是ObjectMapper是非常轻量级的操作,通常适合在每次调用时创建
- 所有配置都是完全线程安全的
在整个工程中涉及到json的处理通用方法:
public class JsonParser {
// 线程安全的,可以采用全局共享
private static volatile ObjectMapper objectMapper = null;
public static String toJson(Object object) {
try {
return objectMapper().writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return