目录
前言
Json数据格式这两年发展的很快,其声称相对XML格式有很对好处:
- 容易阅读;
- 解析速度快;
- 占用空间更少。
不过,JSON 和 XML两者纠结谁优谁劣,这里不做讨论,可以参见知乎上为什么XML这么笨重的数据结构仍在广泛应用?。
最近在项目中,会有各种解析JSON文本的需求,使用第三方Jackson
工具来解析时,又担心当增加会减少字段,会不会出现非预期的情况,因此,研究下jackson
解析json数据格式的代码,很有需要。
Jackson使用工具类
通常,我们对json格式的数据,只会进行解析和封装两种,也就是json字符串--->java对象
以及java对象---> json字符串
。
public class JsonUtils { /** * Logger for this class */ private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class); private final static ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); objectMapper.configure(JsonParser.Feature.INTERN_FIELD_NAMES, true); objectMapper.configure(JsonParser.Feature.CANONICALIZE_FIELD_NAMES, true); objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); } private JsonUtils() { } public static String encode(Object obj) { try { return objectMapper.writeValueAsString(obj); } catch (JsonGenerationException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } catch (JsonMappingException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } catch (IOException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } return null; } /** * 将json string反序列化成对象 * * @param json * @param valueType * @return */ public static <T> T decode(String json, Class<T> valueType) { try { return objectMapper.readValue(json, valueType); } catch (JsonParseException e) { logger.error("decode(String, Class<T>)", e); } catch