解析簡單的 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");