7

My question is pretty much identical to this one, except that I'm using Java/Jackson instead of C#:

In C# how can I deserialize this json when one field might be a string or an array of strings?

My input JSON can be this:

{ "foo": "a string" }

or this:

{ "foo": ["array", "of", "strings" ] }

My class looks like this:

class MyClass {
    public List<String> foo;
}

If the input contains a single string, I want it to become the first entry in the list.

How can I deserialize foo using Jackson? I could write a custom deserializer, which I've done before, but I thought there might be an easier way.

Community
  • 1
  • 1
ccleve
  • 15,239
  • 27
  • 91
  • 157

1 Answers1

5

There is a feature called ACCEPT_SINGLE_VALUE_AS_ARRAY which is turned off by default but you can turn it on:

objectMapper = new ObjectMapper()
        .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

You can also turn it on per case:

class SomeClass {

  @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
  private List<String> items;
  // ...
}
Alireza Mirian
  • 5,862
  • 3
  • 29
  • 48