首页 > 解决方案 > 为 json 字符串创建 JSON 对象 Pojo

问题描述

我有这样的场景,需要使用对象映射器将其转换为对象。因此,我创建了一个如下所示的属性来捕获 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);

标签: javajson

解决方案


您可以使用 @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();
    }
}

推荐阅读