Parse simple JSON object

suggest change

Consider the following JSON string:

  "title": "test",
  "content": "Hello World!!!",
  "year": 2016,
  "names" : [

This JSON object can be parsed using the following code:

try {
    // create a new instance from a string
    JSONObject jsonObject = new JSONObject(jsonAsString);
    String title = jsonObject.getString("title");
    String content = jsonObject.getString("content");
    int year = jsonObject.getInt("year");
    JSONArray names = jsonObject.getJSONArray("names"); //for an array of String objects
} catch (JSONException e) {
    Log.w(TAG,"Could not parse JSON. Error: " + e.getMessage());

Here is another example with a JSONArray nested inside JSONObject:

        "title":"Android JSON Parsing",

This can be parsed with the following code:

JSONObject root = new JSONObject(booksJson);
JSONArray booksArray = root.getJSONArray("books");
JSONObject firstBook = booksArray.getJSONObject(0);
String title = firstBook.getString("title");
int timesSold = firstBook.getInt("times_sold");

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents