1

I use Jackson Library for serialization/deserialization.

I have a Pojo class with a property that i'm looking to be an Array and also support an object (through annotation if possible, for example : @Support(Actualite) ) in the same-time.

@JsonProperty @Support(Actualite)
    private ArrayList<Actualite> actualites;

Is there a way to do this ?

TooCool
  • 10,598
  • 15
  • 60
  • 85

1 Answers1

1

I think what you are asking for is for Jackson to support a property as both an array, and an object for when there is only one value, eg

{ people : { name : "sam" } }

and

{ people : [ { name : "sam" }, { name : "bob" } ] }

In which case you'll want to add this to your mapper:

  mapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true);
  mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

Edit for Spring

You should be able to do something like this if you are using RestTemplate in Spring for Android:

// use false to turn off the default converts
RestTemplate restTemplate = new RestTemplate(false);

// create a new converter with the required features
MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true);
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
converter.setObjectMapper(mapper);

// register that as your converter
restTemplate.getMessageConverters().add(converter);
sksamuel
  • 16,154
  • 8
  • 60
  • 108