Masquitos
Masquitos

Reputation: 536

gson parse object when there is data and array when no data

I use retrofit2 + gson. My question is about when server has data it send me json like:

{
 "next":false,
 "total":4,
 "start":0,
 "rows":[
  {
     "calls":29,
     "new_calls":29,
     "new_quality_calls":10,
     "item":"MzY4NzA3NDA0Mw",
     "sessions":3,
     "calls_per":966.66666666666663
  },
  {
     "calls":15,
     "new_calls":15,
     "new_quality_calls":5,
     "item":"test312312312",
     "sessions":2,
     "calls_per":750
  },
  {
     "calls":0,
     "new_calls":0,
     "new_quality_calls":0,
     "item":"test",
     "sessions":4,
     "calls_per":0
  },
  {
     "calls":0,
     "new_calls":0,
     "new_quality_calls":0,
     "item":"test2",
     "sessions":2,
     "calls_per":0
  }
],
"summary":{
  "sessions":11,
  "calls":44,
  "new_calls":44,
  "new_quality_calls":15,
  "calls_per":400
}
}

But when there is no data, it send me:

{"next":false,"total":0,"start":0,"rows":[],"summary":[]}

The problem is that summary is an object or array is some case. i use this site to make gson calsses http://www.jsonschema2pojo.org/

When i got data its ok, but when there is no data i got an error:

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 56 path

How to solve it automatically by retroft2 (.addConverterFactory(GsonConverterFactory.create())) without manual data parsing?

Upvotes: 0

Views: 74

Answers (1)

Miha_x64
Miha_x64

Reputation: 6363

Add your own converter which will parse AST (readTree), check $.summary type, fix it, and then give this fixed AST to TypeAdapter.

Upvotes: 1

Related Questions