I’m trying to use JSONObject’s put method in for loop. But I’m not getting Expected output.
Expected output:
{"Result":[{"PostOfficeName":"Bhajan Pura","Pincode":"110096"},{"PostOfficeName":"Gokulpuri","Pincode":"110094"}, and so on...]}
OutPut I’m getting:
{"Result":[{"PostOfficeName":"Bhajan Pura","Pincode":"110096"}]}
here is my code:
try { JSONObject obj = new JSONObject(loadJsonfromAssets()); JSONArray arr = obj.getJSONArray("Sheet1"); JSONObject finalObj = new JSONObject(); JSONArray ResultArray = new JSONArray(); JSONObject infoObj = new JSONObject(); for (int i=0; i<arr.length();i++){ JSONObject obj1 = arr.getJSONObject(i); if (obj1.getString("City").equals("New Delhi")){ Log.d("postal", "Found!"); Toast.makeText(this, "" + obj1.getString("Pincode"), Toast.LENGTH_SHORT).show(); infoObj.put("PostOfficeName", obj1.getString("PostOfficeName")); infoObj.put("Pincode",obj1.getString("Pincode")); ResultArray.put(infoObj); } } finalObj.put("Result", ResultArray); System.out.println(finalObj); } catch (JSONException e) { e.printStackTrace(); }
Advertisement
Answer
Have you tried moving the construction of infoObj
inside the loop. By having it outside, you’re maintaining state across loop iterations. I suspect you’re just updating the same json object each time and adding it to the JSON array. Not sure why you NOT getting duplicates because I do when I run your code.
Change it to this makes it “better”
try { JSONObject obj = new JSONObject(loadJsonfromAssets()); JSONArray arr = obj.getJSONArray("Sheet1"); JSONObject finalObj = new JSONObject(); JSONArray ResultArray = new JSONArray(); for (int i=0; i<arr.length();i++){ JSONObject obj1 = arr.getJSONObject(i); if (obj1.getString("City").equals("New Delhi")) { Log.d("postal", "Found!"); Toast.makeText(this, "" + obj1.getString("Pincode"), Toast.LENGTH_SHORT).show(); // move instantiation INSIDE loop JSONObject infoObj = new JSONObject(); infoObj.put("PostOfficeName", obj1.getString("PostOfficeName")); infoObj.put("Pincode",obj1.getString("Pincode")); ResultArray.put(infoObj); } } finalObj.put("Result", ResultArray); System.out.println(finalObj); } catch (JSONException e) { e.printStackTrace(); }