0

Given the following JSON string returned:

String s = "{"errorCode":0,"result":"Processed","trips":[{"tripDestination":"Vancouver","tripStartTime":"07:41"},{"tripDestination":"Montreal","tripStartTime":"08:04"}]}";

I can easily get errorCode and result with something like:

JSONObject jObject;
jObject = new JSONObject(s);

String result = jObject.getString("result");
Log.v("JSON Result", result);

But I do I get to tripDestiation values, knowing it's an array of values within the JSON string?

Robin
  • 9,415
  • 3
  • 34
  • 45
pbeaumier
  • 203
  • 2
  • 7
  • [Json-simple](http://code.google.com/p/json-simple/) is a simple toolkil for converting Json code to Java code – AurA Apr 20 '12 at 12:43

3 Answers3

1

You probably want the getJSONArray() method.

See: http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)

Edit: I would use something like:

ArrayList<String> destinations = new ArrayList<String>();
JSONArray trips = jObject.getJSONArray("trips");
for (int i = 0; i < trips.length(); i++) {
    destinations.add(trips.getJSONObject(i).getString("tripDestination"));
}
Matty K
  • 3,781
  • 2
  • 22
  • 19
1
jObject.getJSONArray("trips").getJSONObject(0).getString("tripDestination");
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
0

You can use:

JSONArray jsonArray = jObject.getJSONArray("trips");

However consider using GSON for parsing json. It is lovely:

public class Class1 {
    private String erroCode;
    private String Processed;
    private Class2[] trips;
}

class Class2 {
    private String tripDestination;
    private String tripStartTime;
}

Gson gson = new Gson();
Class1 object = gson.fromJson(s, Class1.class);
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • Sorry I am not familiar with this term. – Boris Strandjev Apr 20 '12 at 12:51
  • I was wondering if it used reflection to assign the members' values, since in your example they're declared `private` and there is no constructor and no setters. – Matty K Apr 20 '12 at 12:55
  • @MattyK It does use reflection. Some people requested properties would be supported as well. You can read more about that in SO here: http://stackoverflow.com/questions/6203487/why-does-gson-use-fields-and-not-getters-setters – Boris Strandjev Apr 20 '12 at 13:26