0

I'm stuck parsing a nested JSON Array. This should be fairly simple but I can't seem to get it to work.

I have a JSON Array like below:

    {"currentPage":0,
      "totalPages":1,
      "totalSize":1,
      "first":true,
      "last":true,
      "list"[{"date":"2018-11-07T09:34:25.042+0000",
      "lastUpdated":"2018-11-07T09:34:25.266+0000",
      "id"130674,
      "active":true,
      "address":null,
      "storeMobileNumbers": 
      [{"id":130676,"mobile":"+201008005090","version":0
      }]
  }]
}

I'm trying to get the address from the list first, then get the values from storeMobileNumbers.

I have a POJO class for the list, and now I have created a POJO class for the StoreMobileNumbers.

This is what I have right now:

      Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
    Type collectionType = new TypeToken<List<MyStore>>(){}.getType();
    Type collection2 = new TypeToken<List<StoreMobileNumber>>({}.getType();
    JSONObject obj = new JSONObject(json);
       if (obj.has("list")) {
         String myList = obj.get("list").toString();
         list1 = gson.fromJson(myList, collectionType);

         JSONArray obj1 = new JSONArray(list1);
         JSONObject numbersObject = obj1.toJSONObject(obj1);
         String mobileList = 
            numbersObject.get("storeMobileNumbers").toString();
            mobileNumbers = gson.fromJson(mobileList, collection2);
        }

My StoreMobileNumbersClass:

   public class StoreMobileNumber{

   public Long id;
   public String mobile;

   }

So far, my efforts have been unsuccessful. I'm getting the following error:

   org.json.JSONException: No value for storeMobileNumbers

Can someone help me see what I'm missing here?

1
  • incorrect json :( Commented Jan 28, 2019 at 14:06

1 Answer 1

1

Change to following -

String myList = obj.get("list").toString();
     list1 = gson.fromJson(myList, collectionType); // delete this not required

     JSONArray obj1 = new JSONArray(list1);
     JSONObject numbersObject = obj1.getJsonObject(0); // change this to get first object from the JsonArray
     String mobileList = 
        numbersObject.get("storeMobileNumbers").toString();
        mobileNumbers = gson.fromJson(mobileList, collection2);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.