杰克逊映射字符串或简单字符串列表

时间:2017-01-06 11:03:45

标签: java json spring jackson mapper

我正在尝试从API中获取一些Json并将它们解析为一些POJO以与它们一起工作但我有这种情况,我可以获得一个简单的字符串或字符串数​​组的键。

Json看起来像这样:

{
  "offerDisplayCategoryMapping": [
    {
      "offerKey": "EUICC_BASE_ACTIVATION_V01",
      "categoriesKeys": {
        "categoryKey": "Included"
      }
    },
    {
      "offerKey": "EUICC_BASE_ACTIVATION_V02",
      "categoriesKeys": {
        "categoryKey": "Included"
      }
    },
    {
      "offerKey": "EUICC_BASE_ACTIVATION_V03",
      "categoriesKeys": {
        "categoryKey": [
          "Option",
          "Included"
        ]
      }
    }]
}

我正在使用Spring Rest从API中获取结果。我创建了一个代表categoriesKeys的POJO,其中List<String>定义了categoryKey,而我的RestTemplate我定义了ObjectMapper,其中我启用了DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY简单字符串的情况,但这不起作用!!

有什么建议吗?

3 个答案:

答案 0 :(得分:10)

除了已经提到的全局配置之外,还可以在单​​个属性上支持此功能:

public class Container {
  @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
  // ... could also add Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED
  public List<String> tags;
}

答案 1 :(得分:4)

我在Spring之外只用杰克逊试过这个,它按预期工作:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

请注意RestTemplate向其MappingJacksonHttpMessageConverter注册ObjectMapperCheck this answer了解如何配置此ObjectMapper

答案 2 :(得分:2)

因为它是一个键列表,它将起作用。如果in case属性具有单个值而不是如下所示的数组 反序列化功能.ACCEPT_SINGLE_VALUE_AS_ARRAY 将确保将单个属性反序列化为数组

{
    "CategoriesKeys":{
    "categoryKey":{
        "keys":"1"
        }
    }
}



@JsonRootName("CategoriesKeys")
    protected static class CategoriesKeys{

        private CategoryKey categoryKey;
//getters and setters 

}

protected static class CategoryKey{

        private List<String> keys;
//getters and setters 

}

TestClass: 

ObjectMapper mapper=new ObjectMapper();
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
    mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

Output: 

{"CategoriesKeys":{"categoryKey":{"keys":["1"]}}}