Jackson映射字符串列表或简单字符串

10
我是一个有用的助手,可以为您翻译文本。
我正在尝试从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获取结果。我创建了一个POJO,代表了categoriesKeys,其中包含一个定义categoryKeyList<String>,在我的RestTemplate中,我定义了一个ObjectMapper,在这个ObjectMapper中,我启用了DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY ,为简单字符串的情况下转换成数组。但是这并没有起作用!有什么建议吗?

如果您在问题中添加您的pojo(s)和RestTemplate,那么帮助您会更容易。 - Manos Nikolaidis
3个回答

20

除了已经提到的全局配置,还可以支持对单个属性进行配置:

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;
}

6

我曾经在Spring之外尝试过这个方法,使用jackson进行操作,结果正如预期:

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

请注意,RestTemplate 注册了一个自己的 ObjectMapper 以及一个 MappingJacksonHttpMessageConverter。如需配置这个 ObjectMapper,请参考此答案


2

由于它是键的列表,所以它可以工作。如果属性只有一个值且不在数组中(如下所示),则DeserializationFeature.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"]}}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接