首页 > 解决方案 > Android中没有数组名称或节点的JSON解析

问题描述

我有一个没有数组名称的 JSOn 数组,我很困惑如何解析它以及如何制作 JSONObject 或 JSONArray。如果可能的话,请描述一下。

我的 JSON 数组列表是:

[{
name:"Product_fill",
image:"https://something.com/product1.jpg",
title:"Laptop 1"
},
{
name:"Product_fill2",
image:"https://something.com/product2.jpg",
title:"Laptop 2"
},

我的代码是:

    RequestQueue queue= Volley.newRequestQueue(this);
        String Url="http://msomething.com/list.php";
        StringRequest request=new StringRequest(Request.Method.GET, Url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //weatherData.setText("Response is :- ");
                parseData(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                textView.setText("Data Not Received");

            }
        });

        queue.add(request);
        super.onStart();


    }

    private void parseData(String response) {
        try {
            // Create JSOn Object
           JSONObject jsonObject=new JSONObject(response);
           JSONObject main=jsonObject.getJSONObject("array");
        JSONArray jsonArray=jsonObject.getJSONArray("0");

 for(int i=0;i<jsonArray.length();i++)
            {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
textView.setText(jsonObject1.getString("name"));

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

标签: androidjsonandroid-json

解决方案


您可以将响应字符串直接传递给 JSONArray 构造函数,然后使用循环解析数组

JSONArray jsonArray = new JSONArray(response);

提示:我会搜索如何使用其他 json 库,如 Gson 或 Jackson,因为 Android 内置解析器不好。


推荐阅读