-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();
        }
1

2 Answers 2

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();
   }
Sign up to request clarification or add additional context in comments.

2 Comments

Thnx alot Hemant sir for giving me best solution regarding loop
@PradeepSheoran welcome!
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.

6 Comments

super its working for me , thanks alot Ahmed sir.
Sir , This show complete array in a textview so how we collect name, image and title seprately
The for loop as included in your question exactly
by this loop its working for me : for(int i=0;i<jsonArray.length();i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); textView.setText(jsonObject.getString("name")); }
i'm lot of thnxfull
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.