I’m new to JSON and I’m really struggling to parse this layout with GSON in Java
{"time_entries":
[
{"hours":1.0,
"id":311,
"created_on":"2012-11-02T14:53:38Z",
"user":{"id":7,"name":"blah"},
"issue":{"id":266},
"activity":{"id":10,"name":"blah"},
"updated_on":"2012-11-02T14:53:38Z",
"comments":"blah",
"spent_on":"2012-11-02",
"project":{"id":10,"name":"blah"}},
{"hours":6.0,
"id":310,
"created_on":"2012-11-02T13:49:24Z",
"user":{"id":4,"name":"blah"},
"issue":{"id":258},
"activity":{"id":9,"name":"blah"},
"updated_on":"2012-11-02T13:49:24Z",
"comments":"blah",
"spent_on":"2012-11-02",
"project":{"id":11,"name":"blah"
}}
],
"offset":0,
"limit":2,
"total_count":306
}
If it helps it’s the output the Redmine API gives you for time entries.
I’m struggling to understand some of the basic JSON concepts like objects and arrays and I haven’t been able to find an example with a layout similar to this.
My main concern in using the tutorials I have read is that the multiple ID fields will get confused.
What’s the best way to parse this without tying myself in knots?
I’m not set on using Gson and would be happy for a solution using Jackson or the built in library. The end goal is for Android implementation so I would prefer to use use serialization.
Thanks
EDIT:
My attempt at an “object model”
public class TimeResponse {
public List<Time_Entry> time_entries;
@SerializedName("hours")
public String hours;
@SerializedName("id")
public int id;
@SerializedName("created_on")
public String created_on;
@SerializedName("name")
public String name;
@SerializedName("updated_on")
public int updated_on;
public int page;
@SerializedName("comments")
public double comments;
@SerializedName("spent_on")
public String spent_on;
@SerializedName("offset")
public String offset;
@SerializedName("limit")
public String limit;
@SerializedName("total_count")
public String total_count;
}
I’m am unsure as to what I should write for my results list (if I need one) and I’ve have only declared an id and name string once despite it being used multiple times?
I am aware I shouldn’t be using strings for my hours I’m in the process of looking into what the hours field actually contains. I believe the tutorial is slightly out of date in that the last three fields are not represented in the same way now in the Twitter API.
I am not sure what you mean by ‘multiple ID fields’. There is no such thing as an ID in JSON.
Regarding the basic JSON concepts, see http://json.org/:
Object:
Array:
Value:
String:
Number:
Edit:
There is not much you can do to simlify the JSON from your question except pretty-print it:
Perhaps you can see that you have one JSON Object with four name/value pairs:
time_entriesoffsetlimittotal_countThe last three of these have simple numeric values while the first (
time_entries) is an Array of two more Objects. Each one of these two Objects conssits of various name/value pairs. The name/value pairidis just one of these.