zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    dpkg 被中断,您必须手工运行 sudo dpkg –configure -a 解决此问题
    运行wpscan报错Could not find 'nokogiri' (~> 1.8.0)
    理解:jar和war的区别
    AcWing3494. 国际象棋(状压DP)
    AcWing3422. 左孩子右兄弟(树形DP)
    python命名空间
    mysql日志大量报错“original commit timestamp is more recent than the immediate commit timestamp”
    python模块导入
    Centos-Docker镜像制作
    python面向对象之封装
  • 原文地址:https://www.cnblogs.com/badboyf/p/6126511.html
Copyright © 2011-2022 走看看