解析简单的 JSON 对象

请考虑以下 JSON 字符串:

{
  "title": "test",
  "content": "Hello World!!!",
  "year": 2016,
  "names" : [
        "Hannah",
        "David",
        "Steve"
   ]
} 

此 JSON 对象可以用下面的代码进行解析:

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

下面是使用嵌套的 JSONObject 一个 JSONArray 另一个例子:

{
    "books":[
      {
        "title":"Android JSON Parsing",
        "times_sold":186
      }
    ]
}

这可以使用以下代码进行解析:

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