解决ObjectMapper.convertValue()|解决ObjectMapper.convertValue() 遇到的一些问题
源代码:
publicT convertValue(Object fromValue, TypeReference> toValueTypeRef) throws IllegalArgumentException { return (T) _convert(fromValue, _typeFactory.constructType(toValueTypeRef)); }
该方法用于用jackson将bean转换为map 例子:
List sObjects = new ObjectMapper().convertValue(map.get("list"), new TypeReference() { });
微服务中从其他服务获取过来的对象,如果从Object强转为自定义的类型会报错,利用ObjectMapper转换。
ObjectMapper mapper = new ObjectMapper(); DefaultResponse defaultResponse = proxy.getData(); Listresources = ( ) defaultResponse.getData(); //这里的场景是:data是一个Object类型的,但是它其实是一个List ,想把List中的每个对象分别转成可用的对象for (int i = 0; i < serviceDateResources.size(); i++) {Resource resource = mapper.convertValue(resources.get(i), Resource.class); //经过这步处理,resource就是可用的类型了,如果不转化会报错}
在转换过程中有些属性被设置为空,这样就不需要转化
处理方法:
在需要转化的实体类商添加如下注解
@JsonInclude(Include.NON_NULL) @JsonInclude(Include.Include.ALWAYS) 默认 @JsonInclude(Include.NON_DEFAULT) 属性为默认值不序列化 @JsonInclude(Include.NON_EMPTY) 属性为 空(“”) 或者为 NULL 都不序列化 @JsonInclude(Include.NON_NULL) 属性为NULL 不序列化
jackson objectMapper json字符串、对象bean、map、数组list互相转换常用的方法列举:
ObjectMapper mapper = new ObjectMapper();
1.对象转json字符串
User user=new User(); String userJson=mapper.writeValueAsString(user);
2.Map转json字符串
Map map=new HashMap(); String json=mapper.writeValueAsString(map);
3.数组list转json字符串
Student[] stuArr = {student1, student3}; String jsonfromArr =mapper.writeValueAsString(stuArr);
4.json字符串转对象
String expected = "{\"name\":\"Test\"}"; User user = mapper.readValue(expected, User.class);
5.json字符串转Map
String expected = "{\"name\":\"Test\"}"; Map userMap = mapper.readValue(expected, Map.class);
6.json字符串转对象数组List
String expected="[{\"a\":12},{\"b\":23},{\"name\":\"Ryan\"}]"; CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, User.class); ListuserList = mapper.readValue(expected, listType);
7.json字符串转Map数组List