1

I'm new, and attempting to work with the Rest API on setlist.fm from Android Studio, but am having some issues when fitting my GET request results into my Java data model. Particularly, I have modeled "sets" ("set" refers to a set played at a concert) as a Java class. But commonly, I get results back from my HTTP requests that have "set" as an empty string or even an array.

I'll use this following GET request for all Radiohead setlists as an example: http://api.setlist.fm/rest/0.1/artist/a74b1b7f-71a5-4011-9441-d0b5e4122711/setlists.json

Notice how, for the most part, "sets" is an object. But in some instances, it is a String. In other instances it is an array.

My Android Studio is giving me the following error when I try to parse the json with Gson into my data model using the following line of code:

 gson.fromJson(result.toString(),Response.class);

It appears to be failing on an instance where "sets" is shown an empty string rather than an object:

Expected BEGIN_OBJECT but was STRING at line 1 column 942 path $.setlists.setlist[0].sets

Does anyone have advice on how to handle this type of thing? I've noticed it with all artists I've looked up so far. Thanks!

Daniele Segato
  • 12,314
  • 6
  • 62
  • 88
Ryan Miller
  • 315
  • 8
  • 18

2 Answers2

2

Assuming Response is a class you wrote containing the main fields of the json and that at some point in it you have:

@SerializedName("setlist")
private List<MyItem> setlist;

I also assume your MyItem class contains the field:

@SerializedName("sets")
private List<MySet> sets;

if you let Gson parse it it will fail when it found a string instead of a list (-> array) of MySet object.

But you can write a custom TypeAdapter for your MyItem.

There's plenty of documentation about how to write a Gson TypeAdapter, look for it.

Daniele Segato
  • 12,314
  • 6
  • 62
  • 88
0

Use instanceOf operator to determine the type and cast accordingly.

JSONObject response=new JSONObject(res);
if(res.get("key") instanceOf JSONObject)
{
// code for JSONObject
}
else if(res.get("key") instanceOf JSONArray)
{
// code for JSONOArray
}
And so on
Nayan Srivastava
  • 3,655
  • 3
  • 27
  • 49