15

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?

Alireza Mohamadi
  • 751
  • 1
  • 6
  • 22
  • 1
    probably this can help `DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY` http://stackoverflow.com/questions/17003823/make-jackson-interpret-single-json-object-as-array-with-one-element/17004714#17004714 or this : http://stackoverflow.com/search?q=DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY – varren May 11 '16 at 13:59
  • Worked perfectly! Thanks! – Alireza Mohamadi May 11 '16 at 14:39
  • @varren, please post it as answer so question can be closed properly, thanks – Alex Stybaev May 11 '16 at 17:15

1 Answers1

19

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

Community
  • 1
  • 1
varren
  • 14,551
  • 2
  • 41
  • 72