Search code examples
javajsonjacksondeserializationjackson-modules

Jackson desrialize when JsonProperty is sometimes array and sometimes a single Object


I've searched Stack Overflow before posting, but there were no solutions for Jackson.

Here is a server response:

{
  "ok": true,
  "result": [
    {
      "update_id": 489881731,
      //rest 
    },
    {
      "update_id": 489881732,
      //rest
    }
  ]
}

As you see property "result" is an array.

Now this is another response:

{
  "ok": true,
  "result": {
    "id": 211948704,
    "first_name": "ربات ادمین‌های تلگرام",
    "username": "tgAdminsBot"
  }
}

Here "result" is a single object.

This is my class I want to deserialize content to it. I wrote a custom deserializer for TObject of course:

public class Result
{
    private TObject[] result;
    private boolean ok;

    public void setOk (boolean ok) {//code}

    public void setResult (TObject[] result) {//code}


    public TObject[] getResult () {//code}

    public boolean getOk (){//code}
}

So I assumed in my class that "result" is an array of TObjects. Now what can I do? Is using @JsonProperty("result") for two fields which one is an array of TObjects and one is a single TObject OK?

If not what else can I do?


Solution

  • If you enable DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY both

    {"result": []} and

    {"result": {}} can be parsed as

    class Result{
       List result;
    }
    

    Documentation link

    Feature that determines whether it is acceptable to coerce non-array (in JSON) values to work with Java collection (arrays, java.util.Collection) types. If enabled, collection deserializers will try to handle non-array values as if they had "implicit" surrounding JSON array. This feature is meant to be used for compatibility/interoperability reasons, to work with packages (such as XML-to-JSON converters) that leave out JSON array in cases where there is just a single element in array. Feature is disabled by default.

    Demo how to use it for OP input jsons and POJOs:

    ObjectMapper mapper = new ObjectMapper()
    mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    Result result = mapper.readValue(Result.class;
    

    Can be used with @JsonFormat above class or field if you don't like mapper version for some reason

    @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
    

    PS. Other SO questions about this problem: LINK