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");
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练