parsing json array

442 views
Skip to first unread message

grao

unread,
Oct 5, 2010, 11:17:48 PM10/5/10
to google-gson
Hi, I'm new to Gson, would really appreciate any help.
How should I parse this? The "data" array contains values only, the
keys are provided separately in the "fields" array. How do I access
"Los Angeles" and "CA", and then "New York" and "NY"?

{"response":{"total_rows":-1,"data":[["Los Angeles","CA"],["New
York","NY"]], "fields":["city","state"]},"version":"2","status":"ok"}

I tried creating a nested class for data, but again run into the issue
of accessing the values.

Thank you

Pawel Veselov

unread,
Oct 6, 2010, 9:18:49 AM10/6/10
to googl...@googlegroups.com
This is not the best object design, really.
If you think of JSON as of object model, you are doing this:

class Response {
String [] [] data;
String [] fields;
// other stuff
}

Now, when you de-serialize this, you would need to figure how to index
your data.

So, let's add these into your "Response" class:

public String[] getFieldNames() { return fields; }

public int getFieldIndexForName(String fieldName) {
// iterate over 'fields' array, return the index of field found
// or -1 if it wasn't
}

public String getField(int dataRow, int fieldIndex) {
return data[dataRow][fieldIndex];

grao

unread,
Oct 7, 2010, 11:32:22 AM10/7/10
to google-gson
Thank you for the reply, I'll test this out. I did test something
simpler.. In my Java object model of the json, I do create a String[]
[] data double-array, and then in my toString() I just print data[0]
[0] (and tried some others like data[0][1]) every time. I thought at
least something should be printed out, but I still get null.

grao

unread,
Oct 8, 2010, 6:14:43 PM10/8/10
to google-gson
F it... I just wrote my own custom parser... agreed whoever built the
api, not a great object design

thanks for your help
Reply all
Reply to author
Forward
0 new messages