繁体   English   中英

为 json 字符串创建 JSON 对象 Pojo

[英]Creating JSON Object Pojo for json String

我有一个这样的场景,需要使用对象映射器将其转换为对象。因此,我创建了一个如下所示的属性来捕获 OrderDispatchItemDTO。

@JsonProperty("OrderDispatchItemDTO")
    private OrderDispatchItemDTO orderDispatchItemsDTO;

{
  "Message": {

    "MessageData": {
      "OrderDispatchDTO": {
        "StartDateTime": "2017-05-19T02:45:00",
        "Details": {
          "OrderDispatchItemDTO": {
          more json properties
          }
        },
        "EndDateTime": "2017-05-19T05:45:00",
      }
    },
    "StatusID": 1,
  }
}

但是如果 OrderDispatchItemDTO 作为列表出现,那么我的映射器将失败,因为它无法解析 json 字符串

 @JsonProperty("OrderDispatchItemDTO")
        private List<OrderDispatchItemDTO> orderDispatchItemsDTO;




  {
          "Message": {

            "MessageData": {
              "OrderDispatchDTO": {
                "StartDateTime": "2017-05-19T02:45:00",
                "Details": [
                  "OrderDispatchItemDTO": {
                  more json properties
                  },
"OrderDispatchItemDTO": {
                  more json properties
                  }
                ],
                "EndDateTime": "2017-05-19T05:45:00",
              }
            },
            "StatusID": 1,
          }
        }

修复是 mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

您可以使用 @JsonAnySetter 属性并动态设置您的列表。 这是一个例子。 在我的例子中,一个属性可以是一个数字或一个对象,所以这里是我如何简单地解决它:

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
    try {
        if (name.equals("property") && value != null) {
            MyObject t = null;
            if (value instanceof Long) {
                t = new MyObject();
                t.setId((Long) value);
            } else if (value instanceof LinkedHashMap) {
                t = mapper.convertValue(value, MyObject.class);
            }
            //putting t anywhere i.e. setting property
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

暂无
暂无

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

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