需要有关将Json(JsonNode)映射到Java对象

时间:2016-10-17 09:27:13

标签: java json playframework

我们从我们的服务中获得现有的Json响应:

{
  "CustomerInfoResponse": [
    {
      "CustomerInfo": {
        "customerId": "17414101",
        "customerCode": "41020393888"
      }
    },
    {
      "CustomerInfo": {
        "customerId": "17414100",
        "customerCode": "41020393888"
      }
    },
    {
      "CustomerInfo": {
        "customerId": "17414099",
        "customerCode": "41020393888"
      }
    }
  ]
}

我们使用com.fasterxml.jackson.databind.JsonNode在下面的类中映射:

public class CustomerInfoResponse {

    @JsonProperty(value = "CustomerInfoResponse")
    private List<CustomerInfo> customerInfo;


    public List<CustomerInfo> getCustomerInfo() {
        return customerInfo;
    }


    public void setCustomerInfo(final List<CustomerInfo> customerInfo) {
        this.customerInfo = customerInfo;
    }
}

@JsonTypeInfo(include = As.WRAPPER_OBJECT, use = Id.NAME)
public class CustomerInfo {

    private String customerId;
    private String customerCode;


    public String getCustomerId() {
        return customerId;
    }

    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }

    public String getCustomerCode() {
        return customerCode;
    }

    public void setCustomerCode(String customerCode) {
        this.customerCode = customerCode;
    }
}

现在Json格式正在改为下面的格式。我是Json Mapping的新手,我想知道什么会改变我的Java类

{
  "CustomerInfo": [
    {
      "customerId": "112217",
      "customerCode": "41020393888"
    },
    {
      "customerId": "112218",
      "customerCode": "41020393888"
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

要从修改后的Json映射,您应该:

  1. 将成员customerInfo的注释更改为值,该值显示在Json - CustomerInfo 中,而不是之前的 CustomerInfoResponse 。请注意, value = 可能会被省略。

  2. 从CustomerInfo类

  3. 中删除注释

    修改后的Java类应该是这样的:

    public class CustomerInfoResponse {
    
        @JsonProperty("CustomerInfo")
        private List<CustomerInfo> customerInfo;
    
        ...
    }
    
    public class CustomerInfo {
    
        private String customerId;
        private String customerCode;
        ...
    }
    

    没有必要,但使用JsonProperty注释注释类成员是一个好习惯。这使得类中使用的名称与Json键分离。所以,它会是这样的:

     public class CustomerInfo {
        @JsonProperty("customerId")
        private String customerId;
        @JsonProperty("customerCode")
        private String customerCode;
        ...
    }
    

    关于Gson - 你不能在Play中使用它。