【问题标题】:JSON parsing without array name or node in Android [duplicate]Android中没有数组名称或节点的JSON解析[重复]
【发布时间】:2019-01-27 08:42:58
【问题描述】:

我有一个没有数组名称的 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();
        }

【问题讨论】:

标签: android json android-json


【解决方案1】:

试试这个:

 try {
      JSONArray jsonArray = new JSONArray(response);
      for (int i = 0; i <jsonArray.length() ; i++) {
     JSONObject jsonObject = (JSONObject) jsonArray.get(i);  
     textView.setText(jsonObject.getString("name"));   
     }    
    } catch (JSONException e) {
      e.printStackTrace();
   }

【讨论】:

  • 感谢 Hemant 先生为我提供了有关循环的最佳解决方案
  • @PradeepSheoran 欢迎!
【解决方案2】:

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

JSONArray jsonArray = new JSONArray(response);

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

【讨论】:

  • 超级适合我,非常感谢艾哈迈德先生。
  • 先生,这在文本视图中显示了完整的数组,因此我们如何分别收集名称、图像和标题
  • 问题中包含的 for 循环
  • 通过这个循环它为我工作:for(int i=0;i
  • 我很饱
猜你喜欢
  • 2017-06-10
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
  • 2020-01-08
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 2017-05-10
相关资源
最近更新 更多