Reputation: 117
How do I parse this JSON using the GSON Library.
[
{
"id": "1",
"title": "None"
},
{
"id": "2",
"title": "Burlesque"
},
{
"id": "3",
"title": "Emo"
},
{
"id": "4",
"title": "Goth"
}
]
I have tried to do this
public class EventEntity{
@SerializedName("id")
public String id;
@SerializedName("title")
public String title;
public String get_id() {
return this.id;
}
public String get_title() {
return this.title;
}
}
JSONArray jArr = new JSONArray(result);
//JSONObject jObj = new JSONObject(result);
Log.d("GetEventTypes", jArr.toString());
EventEntity[] enums = gson.fromJson(result, EventEntity[].class);
for(int x = 0; x < enums.length; x++){
String id = enums[x].get_id().toString();
}
So far I can get the id using get_id method but I cant seem to assign it to the string id. What is the proper way to go about this?
Upvotes: 2
Views: 1562
Reputation: 18751
Your class EventEntity
is correct, but in order to parse the JSON, you'd better do something like this:
Gson gson = new Gson();
Type listType = new TypeToken<List<EventEntity>>() {}.getType();
List<EventEntity> data = gson.fromJson(result, listType);
Then you'll have a List
with all your EventEntity
objects into the variable data
, so you can access the values just with:
String id = data.get(i).get_id();
String title = data.get(i).get_title();
Upvotes: 4