杰克逊 - 反序列化没有属性名称的数组

时间:2017-04-19 13:40:55

标签: java json jackson json-deserialization

我有来自shipcloud.io的以下JSON响应:

[
  {
    "name": "dhl",
    "display_name": "Deutsche Post DHL",
    "services": [
      "standard",
      "returns",
      "one_day",
      "one_day_early"
    ],
    "package_types": [
      "parcel",
      "bulk"
    ]
  },
  {
    "name": "dpag",
    "display_name": "Deutsche Post",
    "services": [
      "standard"
    ],
    "package_types": [
      "letter",
      "parcel_letter",
      "books"
    ]
  },
  {
    "name": "dpd",
    "display_name": "DPD - Dynamic Parcel Distribution",
    "services": [
      "standard",
      "returns",
      "one_day",
      "one_day_early"
    ],
    "package_types": [
      "parcel",
      "parcel_letter"
    ]
  }
]

如何用Jackson反序列化这个JSON数组?通常我使用简单的POJO并定义 列表/数组的属性名称(例如@JsonProperty(“blub”))。问题是,这里没有使用属性名称...... 我尝试使用空属性名称,但它没有用。 我刚刚收到此错误消息:

Can not deserialize instance of Response.CarriersResponse out of 
START_ARRAY token

3 个答案:

答案 0 :(得分:1)

如果您想使用jackson,这是适合我的解决方案:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);

答案 1 :(得分:0)

您正在反序列化该类型的多个对象,因此您需要将其作为列表进行,例如

// somewhere in an example TypeReferences class
public static final TypeReference<List<Response.CarriersResponse>> CARRIER_RESPONSES = new TypeReference<List<Response.CarriersResponse>>() {
};

// elsewhere where you're calling the mapper
List<Response.CarriersResponse> responses = mapper.readValue(text, TypeReferences.CARRIER_RESPONSES);

您可以就地实例化它,但这是性能与总内存消耗之间的设计决策。

答案 2 :(得分:0)

尝试反序列化为Response.CarriersResponse[]类。

Response.CarriersResponse[] responses = mapper.readValue(text, Response.CarriersResponse[].class);