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 生日广州男生祝福语简短