-1

I have a JSOn array without array name and I'm confused how to parse it and how to make JSONObject or JSONArray. If possible then please describe it.

My JSON Array list is:

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

and my code is :

    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();
        }
halfer
  • 19,824
  • 17
  • 99
  • 186
Pradeep Sheoran
  • 493
  • 6
  • 15
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Aug 21 '18 at 09:36

2 Answers2

1

You can pass the response string to the JSONArray constructor directly and then parse the array using a loop

JSONArray jsonArray = new JSONArray(response);

Tip: I would search how to use other json libraries like Gson or Jackson as the Android built-in parser is not good.

Ahmed Hegazy
  • 12,395
  • 5
  • 41
  • 64
1

Try this:

 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 Parmar
  • 3,924
  • 7
  • 25
  • 49