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 送给学长毕业祝福语简短