8

我有一些 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
                        }
                    ]
                }
            ]
        }
    ]
}
4

6 回答 6

12

只有当您的 json 数据大小小于 1MB 时,您才能使用 JSON Object/JSON Array。否则,您应该使用 JSONReader。JSONReader 实际上使用流式方法,而 JSONObject 和 JSONArray 最终一次将所有数据加载到 RAM 上,这在更大的 json 的情况下会导致 OutOfMemoryException。

于 2014-06-16T13:14:23.187 回答
6

当您必须使用嵌套对象时,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.htmlhttp://www.androidhive.info/2012/01/android-json-parsing-tutorial/

于 2013-02-07T03:22:32.927 回答
3

如果我这样做,我会将整个字符串解析为 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"));
于 2013-02-07T03:24:59.313 回答
1

这是一个使用 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";
}
于 2015-09-02T12:07:45.037 回答
0

您发布的示例 JSON 数据似乎不遵循 JSON 的数据结构。您将需要完全按照Mustafa 发布的第三个链接中所教的方式构建数据。这是一个非常棒的教程。我按照步骤操作,它确实有效!

于 2013-02-07T03:32:49.430 回答
-2

这是我用来解析嵌套 JSON 对象中所有记录的代码。

使用 BSON 时,它以object. 因此,为了使用与实际类型(intDocumentArrayList等)关联的方法,您必须将返回值强制转换为预期的类型。

 // 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")));
于 2019-10-04T19:03:58.273 回答