我有一些JSON(如下所示),我试图解析整个JSON,每个对象将是一个声明下面变量的类的新实例.做这个的最好方式是什么?我应该使用JSONReader还是使用JSONObject和JSONArray.我一直在阅读一些教程并询问一些一般性问题,但我还没有看到任何如何解析这样的数据的例子.
{
"id": 356,
"hassubcategories": true,
"subcategories": [
{
"id": 3808,
"CategoryName": "Current Products",
"CategoryImage": null,
"hassubcategories": true,
"subcategories": [
{
"id": 4106,
"CategoryName": "Architectural",
"CategoryImage": "2637",
"hassubcategories": true,
"subcategories": [
{
"id": 391,
"CategoryName": "Flooring",
"CategoryImage": "2745",
"hassubcategories": false
}
]
}
]
},
{
"id": 3809,
"CategoryName": "Non-Current Products",
"CategoryImage": null,
"hassubcategories": true,
"subcategories": [
{
"id": 4107,
"CategoryName": "Desk",
"CategoryImage": "2638",
"hassubcategories": true,
"subcategories": [
{
"id": 392,
"CategoryName": "Wood",
"CategoryImage": "2746",
"hassubcategories": false
}
]
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
Yas*_*Ali 10
仅当json数据的大小小于1MB时,才能使用JSON Object/JSON Array.否则你应该使用JSONReader.JSONReader实际上使用流方法,而JSONObject和JSONArray最终会立即加载RAM上的所有数据,如果更大的json,则会导致OutOfMemoryException.
当您必须使用嵌套对象时,GSON是最简单的方法.
像这样:
//after the fetched Json:
Gson gson = new Gson();
Event[] events = gson.fromJson(yourJson, Event[].class);
//somewhere nested in the class:
static class Event{
int id;
String categoryName;
String categoryImage;
boolean hassubcategories;
ArrayList<Event> subcategories;
}
Run Code Online (Sandbox Code Playgroud)
您可以查看本教程, http://androidsmith.com/2011/07/using-gson-to-parse-json-on-android/ 或http://www.javacodegeeks.com/2011/01/android-json -parsing-gson-tutorial.html或http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
如果我这样做,我会将整个字符串解析为 JSONObject
JSONObject obj = new JSONObject(str);
Run Code Online (Sandbox Code Playgroud)
然后我看到你的子类别是一个 JSONArray。所以我会像这样转换它
JSONArray arr = new JSONArray(obj.get("subcategories"));
Run Code Online (Sandbox Code Playgroud)
用这个你可以做一个循环并实例化你的类对象
for(int i = 0; i < arr.length; i++)
JSONObject temp = arr.getJSONObject(i);
Category c = new Category();
c.setId(temp.get("id"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40257 次 |
| 最近记录: |