网上大部分的转换都使用阿里的fastjson,这里使用com.fasterxml.jackson.databind.ObjectMapper
。
- 将对象转为JSON字符串
ObjectMapper objectMapper = new ObjectMapper();
String str = objectMapper.writeValueAsString(javaObj);
- 将JSON字符串转为Map
JavaType valueType = objectMapper.getTypeFactory()
.constructParametricType(HashMap.class, String.class, Object.class);
HashMap<String, Object> map = objectMapper.readValue(str, valueType);
- 将JSON字符串转为List
JavaType valueType = objectMapper.getTypeFactory()
.constructParametricType(ArrayList.class, Person.class);
List<Person> list = objectMapper.readValue(str, valueType);
网友评论