Jackson Mapping List of String or simple String

醉酒当歌 提交于 2019-12-09 17:02:46

问题


I'm trying to get some Json from an API and parse them into some POJO's to work with them but i have this case where i can get for a key a simple String or an arrayList of Strings.

The Json looks like this :

{
  "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"
        ]
      }
    }]
}

I'm using Spring Rest to get the result from the API. I created a POJO that represents categoriesKeys with a List<String> that defines categoryKey and in my RestTemplate I defined an ObjectMapper where i enabled DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY for the case of simple strings but this doesn't work!!

Any suggestions?


回答1:


In addition to global configuration already mentioned, it is also possible to support this on individual properties:

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



回答2:


I have tried this with just jackson outside Spring and it works as expected with:

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

Mind that RestTemplate registers a MappingJacksonHttpMessageConverter with it's own ObjectMapper. Check this answer for how to configure this ObjectMapper.




回答3:


Since it is a List of keys it will work. if in case property has single value and not in array like below DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY will ensure deserializing single property as a 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"]}}}


来源:https://stackoverflow.com/questions/41504296/jackson-mapping-list-of-string-or-simple-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!