objectMapper.convertValue

objectMapper.convertValue
将linkedHashMap转成对象使用的的方法

ObjectMapper处理从远程获取的Object对象

微服务中从其他服务获取过来的对象,如果从Object强转为自定义的类型会报错,利用ObjectMapper转换。

ObjectMapper mapper = new ObjectMapper();
DefaultResponse defaultResponse = proxy.getData();
List<Resource> resources = (<Resource>) defaultResponse.getData();  //这里的场景是:data是一个Object类型的,但是它其实是一个List<Resouce>,想把List中的每个对象分别转成可用的对象
for (int i = 0; i < serviceDateResources.size(); i++) {
    Resource resource = mapper.convertValue(resources.get(i), Resource.class);   //经过这步处理,resource就是可用的类型了,如果不转化会报错
}

上面转换的过程中,如果返回的字段你不是都需要,需要忽略其中的几个字段,在自定义的类中添加如下:

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Resource {
//  private Integer orderId; //提供有这个参数,但是不想获取
  private Integer otrerFiled;
}

或者下面方法:这两种方法不用添加注解

 
一:ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD,Visibility.ANY);
   mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
二:ObjectMapper objectMapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

ObjectMapper可以实现对象到json等其他格式的互转。如果向将java对象转成Json格式,可以用:

 ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(object);

会有JsonProcessingException异常,需要自己处理。在转换的过程中,有可能有的属性被设成空就不序列化等的需求,可以在类的属性上或直接在类上加上一下注解。用在属性上就是只针对一个属性,用在类上就是针对类里的所有属性。

@JsonInclude(Include.NON_NULL) 
@JsonInclude(Include.Include.ALWAYS) 默认 
@JsonInclude(Include.NON_DEFAULT) 属性为默认值不序列化 
@JsonInclude(Include.NON_EMPTY) 属性为 空(“”) 或者为 NULL 都不序列化 
@JsonInclude(Include.NON_NULL) 属性为NULL 不序列化 

json转成Object 及 Object转json

    DefaultResponse  response = mapper.readValue(result, DefaultResponse.class); 
  String Json =  mapper.writeValueAsString(student1); 

mapper.readValue()过程中,如果result中的字段比DefaultResponse字段多会报错,忽略多余的字段在DefaultResponse中添加下面注解。

@JsonIgnoreProperties(ignoreUnknown = true)
原文地址:https://www.cnblogs.com/qingmuchuanqi48/p/13224173.html