Parse simple JSON object
suggest changeConsider the following JSON string:
{ "title": "test", "content": "Hello World!!!", "year": 2016, "names" : [ "Hannah", "David", "Steve" ] }
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:
{ "books":[ { "title":"Android JSON Parsing", "times_sold":186 } ] }
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");
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents