How to extract multiple JSON Objects into String How to extract multiple JSON Objects into String json json

How to extract multiple JSON Objects into String


try this and see how it works for you,

BufferedReader in   = new BufferedReader(new FileReader("foo.in"));ArrayList<JSONObject> contentsAsJsonObjects = new ArrayList<JSONObject>();while(true){  String str = in.readLine();  if(str==null)break;  contentsAsJsonObjects.add(new JSONObject(str));}for(int i=0; i<contentsAsJsonObjects.size(); i++) {   JSONObject json = contentsAsJsonObjects.get(i);  String lat = json.getString("Lat");   String lng = json.getString("Lng");   Log.i("TAG", lat + lng) }


What you do is you are loading multiple JSON objects into one JSON object. This does not make sense -- it is logical that only the first object is parsed, the parser does not expect anything after the first }. Since you want to loop over the loaded objects, you should load those into a JSON array.

If you can edit the input file, convert it to the array by adding braces and commas

[    {},    {}]

If you cannot, append the braces to the beginning of the StringBuilder and append comma to each loaded line. Consider additional condition to eliminate exceptions caused by inpropper input file.

Finally you can create JSON array from string and loop over it with this code

JSONArray array = new JSONArray(contentsAsString);for (int i = 0; i < array.length(); ++i) {    JSONObject object = array.getJSONObject(i);}