1

I have a json like below :

{"key":{"a":"aValue"}}

"key" can contain json object as well as json array. i have created following java object to map this json :

Class Output {
  private List<DummyObject> key;
  // setter, getting ommited
}
Class DummyObject {
  private String a;
}

So, i want if json is

{"key":[{"a":"val1"},{"a":"val2"}]}

"key" property of Output class should contain a list of 2 objects, and when the json is

{"key":{"a":"val1"}}

"key" should contain a list of 1 object only.

I have tried using deserializer but it does not work. Also, i do not want to deserialise DummyObject myself.

Gaurav Singh
  • 287
  • 6
  • 19
  • Can you post the code you tried? – pedromss Aug 28 '17 at 16:41
  • 2
    Possible duplicate of [Make Jackson interpret single JSON object as array with one element](https://stackoverflow.com/questions/17003823/make-jackson-interpret-single-json-object-as-array-with-one-element) – tima Aug 28 '17 at 16:41

2 Answers2

0

Try enabling the Jackson deserialization feature ACCEPT_SINGLE_VALUE_AS_ARRAY.

final ObjectMapper mapper = new ObjectMapper()
        .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
Adam
  • 43,763
  • 16
  • 104
  • 144
0

Considering {"key":[{"a":"val1"},{"a":"val2"}]}

The issue is not in your model with the Output;

Class Output {
  private List<DummyObject> key;
  // setter, getting ommited
}

Since this represents that key as a json array.

But you might want to update the DummyObject:

Class DummyObject {
  private String a;
}

to

Class DummyObject {
  private Map<String,String> a;
}

Since {"a":"val1"} is not a valid representation of DummyObject or even String a.


Additionally as pointed out by @tima, for varying length of your JSONArray for "key", you must take a look at how to Make Jackson interpret single JSON object as array with one element


The final clause of your question:

Also, I do not want to deserialize DummyObject myself.

You can try and update the Output model(not sure if that would be beneficial from performance perspective) as:

Class Output {
  private List<Map<String, String>> key;
  // setter, getting ommited
}
Naman
  • 27,789
  • 26
  • 218
  • 353