代码之家  ›  专栏  ›  技术社区  ›  Keshav

在Java中反序列化响应时更改属性名称

  •  2
  • Keshav  · 技术社区  · 6 年前

    来自API的JSON响应:

    {
       "result":[
          {
             "ResultType":"SUCCESS"
          }
       ]
    }
    

    转换为ResultClass.class后:

    {
       "result":[
          {
             "resultType":null
          }
       ]
    }
    

    转换为ResultClass.class后的预期输出:

    {
       "result":[
          {
             "resultType":"SUCCESS"
          }
       ]
    }
    

    我正在与第三方API集成。我想在反序列化时更改属性名。我在字段getter和setter上尝试了@JsonProperty。但该值未反映在字段resultType中。

    结果类.java

    @JsonProperty("result")
    List<TestClass> result = new ArrayList<>();
    
    public List<TestClass> getResult() {
            return result;
    }
    
    public void setResult(List<TestClass> result) {
        this.result = result;
    }
    

    测试类.java

    @JsonProperty("ResultType")
    private String resultType;
    
    public String getResultType() {
            return resultType;
    }
    
    public void setResultType(String resultType) {
            this.resultType = resultType;
    }
    

    注意:我试过JsonObject,它工作正常。我正在使用HttpClient和HttpResponse发出请求。Jackson版本:2.5.0

    1 回复  |  直到 6 年前
        1
  •  0
  •   Benoit    6 年前

    提供两种解决方案:

    1.使反序列化不区分大小写

    在对象映射器上添加此功能:

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    

    更改属性名称的步骤 ResultType resultType ,你应该两者兼用 @JsonGetter @JsonSetter

    import com.fasterxml.jackson.annotation.JsonGetter;
    import com.fasterxml.jackson.annotation.JsonSetter;
    
    public class TestClass {
    
        private String resultType;
    
        @JsonGetter("resultType")
        public String getResultType() {
            return resultType;
        }
    
        @JsonSetter("ResultType")
        public void setResultType(String resultType) {
            this.resultType = resultType;
        }
    }