简体   繁体   中英

Spring Jackson convert json object to java array

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.

Try enabling the Jackson deserialization feature ACCEPT_SINGLE_VALUE_AS_ARRAY .

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM