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");
热门推荐
10 毛笔哥哥结婚祝福语简短
11 向国庆送祝福语简短
12 建队节祝福语简短
13 朋友喜得外孙简短祝福语
14 小店营业的祝福语简短
15 餐饮生日祝福语简短独特
16 鲜花英语祝福语卡片简短
17 男朋友暴富祝福语简短
18 婶婶拜年祝福语大全简短