ObjectMapper可以用来实现Java对象跟json的转换,节省大量的字符串拼接/解析工作,在实际使用中遇到一些问题,总结如下。
读取List
比如ip是一个ip列表List,以下代码用于从json字符串中读取List对象:
ObjectMapper objectMapper = ObjectMapperInit.init(new ObjectMapper());
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, String.class);
try {
return objectMapper.readValue(ip, javaType);
} catch (IOException e) {
log.warn("exception while parsing data, data:{}, exception:{}", ip, e);
}