![](/img/trans.png)
[英]How Parse JSON using GSON WHen object is either JSONObject or JSONArray
[英]Parse JSON data using JSONReader or JSONObject/JSONArray
我有一些 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
}
]
}
]
}
]
}
僅當 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;
}
您可以查看本教程, 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);
然后我看到你的子類別是一個 JSONArray。 所以我會像這樣轉換它
JSONArray arr = new JSONArray(obj.get("subcategories"));
有了這個,你可以做一個循環並實例化你的類對象
for(int i = 0; i < arr.length; i++)
JSONObject temp = arr.getJSONObject(i);
Category c = new Category();
c.setId(temp.get("id"));
這是使用 Gson 通過 JsonReader 對對象數組列表進行建模的簡單示例:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textviewtest);
Task task = new Task();
task.execute();
}
private class Task extends AsyncTask<Void, Void, ArrayList<Flower>> {
@Override
protected ArrayList<Flower> doInBackground(Void... params) {
ArrayList<Flower> arrayFlowers = new ArrayList<Flower>();
Flower[] f = null;
try {
String uri = "http://services.hanselandpetal.com/feeds/flowers.json";
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
Gson gson = new Gson();
JsonReader reader = new JsonReader(new InputStreamReader(con.getInputStream()));
f = gson.fromJson(reader, Flower[].class);
for (Flower flower : f) {
arrayFlowers.add(flower);
}
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
return arrayFlowers;
}
@Override
protected void onPostExecute(ArrayList<Flower> result) {
StringBuilder sb = new StringBuilder();
for (Flower flower : result) {
sb.append(flower.toString());
}
tv.setText(sb.toString());
}
}
和我建模的對象:
public class Flower {
private String category;
private double price;
private String instructions;
private String photo;
private String name;
private int productId;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
@Override
public String toString() {
return getProductId() + " : " + name + "\n" + price + "$" + "\n" + "\n";
}
您發布的示例 JSON 數據似乎不遵循 JSON 的數據結構。 您將需要以與 Mustafa 發布的第三個鏈接中所教的完全相同的方式構建數據。 這是一個非常棒的教程。 我按照步驟操作,確實有效!
這是我用來解析嵌套 JSON 對象中所有記錄的代碼。
使用 BSON 時,它將值作為object
返回。 因此,為了使用與實際類型( int
、 Document
、 ArrayList
等)關聯的方法,您必須將返回值轉換為預期的類型。
// import java.util.ArrayList;
// import org.bson.Document;
Document root = Document.parse("{ \"id\" : 356, \"hassubcategories\" : true, \"subcategories\" : [{ \"id\" : 3808, \"CategoryName\" : \"Current Products\", \"CategoryImage\" : \"image.img\", \"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\" : \"image.img\", \"hassubcategories\" : true, \"subcategories\" : [{ \"id\" : 4107, \"CategoryName\" : \"Desk\", \"CategoryImage\" : \"2638\", \"hassubcategories\" : true, \"subcategories\" : [{ \"id\" : 392, \"CategoryName\" : \"Wood\", \"CategoryImage\" : \"2746\", \"hassubcategories\" : false }] }] }] }");
System.out.println((root.get("id")));
System.out.println((root.get("hassubcategories")));
System.out.println((((Document)((ArrayList)root.get("subcategories")).get(0)).get("id")));
System.out.println(((String)((Document)((ArrayList)root.get("subcategories")).get(0)).get("CategoryName")));
System.out.println(((String)((Document)((ArrayList)root.get("subcategories")).get(0)).get("CategoryImage")));
System.out.println((((Document)((ArrayList)root.get("subcategories")).get(0)).get("hassubcategories")));
System.out.println((((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("id")));
System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("CategoryName")));
System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("CategoryImage")));
System.out.println((((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("hassubcategories")));
System.out.println((((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("id")));
System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("CategoryName")));
System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("CategoryImage")));
System.out.println((((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("hassubcategories")));
System.out.println((((Document)((ArrayList)root.get("subcategories")).get(1)).get("id")));
System.out.println(((String)((Document)((ArrayList)root.get("subcategories")).get(1)).get("CategoryName")));
System.out.println(((String)((Document)((ArrayList)root.get("subcategories")).get(1)).get("CategoryImage")));
System.out.println((((Document)((ArrayList)root.get("subcategories")).get(1)).get("hassubcategories")));
System.out.println((((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("id")));
System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("CategoryName")));
System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("CategoryImage")));
System.out.println((((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("hassubcategories")));
System.out.println((((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("id")));
System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("CategoryName")));
System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("CategoryImage")));
System.out.println((((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("hassubcategories")));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.