Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Mapping List of String or simple String

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?

like image 796
Habchi Avatar asked Jan 06 '17 11:01

Habchi


People also ask

Why do we use ObjectMapper?

ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model ( JsonNode ), as well as related functionality for performing conversions.

Is ObjectMapper thread safe?

Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls.

How does ObjectMapper readValue work?

The simple readValue API of the ObjectMapper is a good entry point. We can use it to parse or deserialize JSON content into a Java object. Also, on the writing side, we can use the writeValue API to serialize any Java object as JSON output.

Does Jackson ObjectMapper use reflection?

Without any annotations, the Jackson ObjectMapper uses reflection to do the POJO mapping. Because of the reflection, it works on all fields regardless of the access modifier.


2 Answers

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;
}
like image 183
StaxMan Avatar answered Sep 21 '22 00:09

StaxMan


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.

like image 24
Manos Nikolaidis Avatar answered Sep 21 '22 00:09

Manos Nikolaidis