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?

1
  • Json-simple is a simple toolkil for converting Json code to Java code Commented Apr 20, 2012 at 12:43

3 Answers 3

1
jObject.getJSONArray("trips").getJSONObject(0).getString("tripDestination");
Sign up to request clarification or add additional context in comments.

Comments

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"));
}

Comments

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);

3 Comments

Sorry I am not familiar with this term.
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.
@MattyK It does use reflection. Some people requested properties would be supported as well. You can read more about that in SO here: stackoverflow.com/questions/6203487/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.