1

enter image description here

Above is the json response I am receiving from a url. There are repeated json objects in the response at the same level without a parent json array, I believe that these objects should be within a josn array so one can loop through the objects to access their information.

Is it really an error of missing json array? if not then how can be looped through and receive information in such scenario. Thanks for your time and help.

shehzy
  • 2,215
  • 3
  • 25
  • 45

3 Answers3

2

How can be looped through and receive information in such scenario ?

You should use ITERATOR for this case .

FYI

Iterator is a way to traverse the data over the collection objects.

JSONObject jOBJECT = new JSONObject(success);
           Iterator  iteratorObj = jOBJECT.keys();
            while (iteratorObj.hasNext())
            {
                String getJsonObj = (String)iteratorObj.next();
                System.out.println("Key: " + Key + "------>" + getJsonObj); // 78,40,121,132
            }
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
  • 1
    Thanks @Amiya, it looks good and I feel it will work for me, let me try it to set it as correct one. – shehzy Jul 15 '17 at 07:06
0

Here is the detailed solution for such pattern of objects in the service response.

https://stackoverflow.com/a/12870643/1925394

shehzy
  • 2,215
  • 3
  • 25
  • 45
-1

this code maybe can help you:

try {
            String data="";//this is you json
            JSONObject jsonObject=new JSONObject(data);
            JSONArray messages = jsonObject.getJSONArray("message");//get a array
            //loop the arrat to output
            for (int i = 0; i  < messages.length(); i++) {
                JSONObject msg=messages.getJSONObject(i);
                String id= msg.getString("id");
                String username= msg.getString("username");
                System.out.println("id:"+id+",username:"+username);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

but,I advise you don't use this in your project, you can consider Gson ,use this you can transfer json to java model,and then it's easy to use.

Mr.jie
  • 42
  • 6