【问题标题】:Parse JSON data using JSONReader or JSONObject/JSONArray使用 JSONReader 或 JSONObject/JSONArray 解析 JSON 数据
【发布时间】:2013-02-07 03:14:31
【问题描述】:

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

【问题讨论】:

    标签: java android json


    【解决方案1】:

    仅当您的 json 数据大小小于 1MB 时,您才可以使用 JSON Object/JSON Array。否则,您应该使用 JSONReader。 JSONReader 实际上使用流式方法,而 JSONObject 和 JSONArray 最终会一次将所有数据加载到 RAM 上,如果 json 较大,则会导致 OutOfMemoryException。

    【讨论】:

    • You can use JSON Object/ JSON Array only if the size of your json data is less than 1MB此信息在哪里正式记录?
    • @AADProgramming 一些线索来自遇到某个问题并且无法从官方文档中找到解决方案的开发人员:-)
    【解决方案2】:

    当您必须使用嵌套对象时,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/

    【讨论】:

      【解决方案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"));
      

      【讨论】:

        【解决方案4】:

        这是一个使用 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";
        }
        

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            【解决方案6】:

            这是我用来解析嵌套 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")));
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多