Android 解析简单的JSON对象
示例
考虑以下JSON字符串:
{
"title": "test",
"content": "你好,世界!!!",
"year": 2016,
"names" : [
"Hannah",
"David",
"Steve"
]
}可以使用以下代码来解析此JSON对象:
try {
//从字符串创建新实例
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"); //用于String对象的数组
} 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");