asaproG
asaproG

Reputation: 35

Android Parse multiple JSON arrays

I tried to parse multiple JSON arrays that my server returns to my application.

The structure of the returned message from the server looks like this:

[ json objects ][ json objects ]

returned message :

[{"latitude":"44.33","longitude":"44.33","name":"test1","Notification":"true"}][{"latitude":"44.33","longitude":"44.33","name":"test2","Notification":"false"}]

Now I tried to parse this and get the Notification status (true / false) but I did not get the item i needed.

  try {

       JSONArray jr = new JSONArray(answer);
       JSONObject jb = (JSONObject)jr.getJSONObject(0);
       JSONArray nof = jb.getJSONArray("Notification");
       Log.d("Json", String.valueOf(nof));
  }catch(Exception e)
  {
       e.printStackTrace();
  }

I would be happy if someone can help me to understand what I need todo to achieve my mission.

Upvotes: 0

Views: 3253

Answers (3)

Ankit Aman
Ankit Aman

Reputation: 1009

Create a POJO of Response lets say Notification.java

JSONArray resultArray = response.getJSONArray("result");// your json response 

// using Gson Library By google

compile 'com.google.code.gson:gson:2.7.0'

List<Notification> notificationList = new    Gson().fromJson(String.valueOf(resultArray),Notification.class);

Upvotes: 0

rafsanahmad007
rafsanahmad007

Reputation: 23881

Your Json response is invalid...

This is the valid JSON:

  [
    [{
        "latitude": "44.33",
        "longitude": "44.33",
        "name": "test1",
        "Notification": "true"
    }],
    [{
        "latitude": "44.33",
        "longitude": "44.33",
        "name": "test2",
        "Notification": "false"
    }]
  ]

to parse it:

try{
JSONArray json = new JSONArray(answer);
for(int i=0;i<json.length();i++){
     JSONArray array = json.getJSONArray(i);
         for(int i=0;i<array.length();i++){
            JSONObject object = array.getJSONObject(i);
            String Notification = object.getString("Notification");

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

Upvotes: 2

Alberto Brambilla
Alberto Brambilla

Reputation: 378

That Json response can't be parsed as a whole. Formally it is not json valid, there are two json arrays that concatenate like that do not make a valid json.

You can wrap those array in a unique json object and that object is now parsable with your code.

{"array1":[],"array2":[]}

Then you can instantiate the jsonObject and get each array separately with their name

Upvotes: 0

Related Questions