简体   繁体   English

Jackson objectMapper 将不同的 json 属性映射到同一个 pojo

[英]Jackson objectMapper mapping different json properties to same pojo

I have a very simple json which I am trying to map to an object.我有一个非常简单的 json,我试图将它映射到一个对象。

JSON : JSON :

[
    {
        "cust_lpid": "0119b9f7f99ad2161de7b0b",
        "cust_uid": "soumavtestflow"
    }
]

My Mapper Class:我的映射器类:

@JsonIgnoreProperties(ignoreUnknown = true)
public class CustomerSegmentRequest {

    @JsonProperty("LPID")
    String cust_lpid;
    @JsonProperty("UserId")
    String cust_uid;

    public String getCust_lpid() {
        return cust_lpid;
    }
    public void setCust_lpid(String cust_lpid) {
        this.cust_lpid = cust_lpid;
    }
    public String getCust_uid() {
        return cust_uid;
    }
    public void setCust_uid(String cust_uid) {
        this.cust_uid = cust_uid;
    }
}

When I do a当我做一个

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
LPIDCustIDMapper[] custSegResp = objectMapper.readValue(responseBody,CustomerSegmentRequest [].class);

I don't get any values populated in custSegResp.我没有在 custSegResp 中填充任何值。

However when i remove the @JsonProperty it works.但是,当我删除@JsonProperty它可以工作。 I need the json property name to map an incoming request and hence don't wanna create a separate mapping class.我需要 json 属性名称来映射传入的请求,因此不想创建单独的映射类。 Is there a way to achieve the same?有没有办法实现相同的目标?

use @JsonAlias使用@JsonAlias

@JsonIgnoreProperties(ignoreUnknown = true)
public class CustomerSegmentRequest {

   @JsonAlias({"cust_lpid", "LPID" })
   String cust_lpid;

   @JsonAlias({"cust_uid", "UserId" })
   String cust_uid;

   public String getCust_lpid() {
      return cust_lpid;
   }

   public void setCust_lpid(String cust_lpid) {
      this.cust_lpid = cust_lpid;
   }

    public String getCust_uid() {
      return cust_uid;
   }

    public void setCust_uid(String cust_uid) {
       this.cust_uid = cust_uid;
   }
}

@JsonProperty("keyName") is to specify what is the key is the JSON which maps to this field. @JsonProperty("keyName")用于指定映射到该字段的 JSON 的key是什么。

The reason it works without it is, without it Jackson tries to first match via getters/setters after removing the get / set prefix keys and normalizing the case ( getAbCd -> abCd ), which in your case gives the keys as in the JSON.没有它它工作的原因是,如果没有它,Jackson 在删除get / set前缀键并规范化案例( getAbCd -> abCd )后尝试首先通过 getter/setter 进行匹配,在您的情况下,它给出了 JSON 中的键。

You need to modify your @JsonProperty("LPID") to @JsonProperty("cust_lpid") or if you need to map to multiple keys use @JsonAlias({"cust_lpid", "LPID" })您需要将@JsonProperty("LPID")修改为@JsonProperty("cust_lpid")或者如果您需要映射到多个键,请使用@JsonAlias({"cust_lpid", "LPID" })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM