I get this line from the server:

{ "towns": [ "{\"name\":\"Berlin\",\"id\":1}", "{\"name\":\"Munhen\",\"id\":3}", "{\"name\":\"Koln\",\"id\":4}", "{\"name\":\"Bremen\",\"id\":5}", "{\"name\":\"Shtetgard\",\"id\":6}", "{\"name\":\"Drezden\",\"id\":7}", "{\"name\":\"Bonn\",\"id\":8}", "{\"name\":\"Augsburg\",\"id\":9}", "{\"name\":\"Kil\",\"id\":10}", "{\"name\":\"Potsdam\",\"id\":13}", "{\"name\":\"Rüdersdorf\",\"id\":14}" ] } 

I start to disassemble it:

 JSONObject townsObj = null; Log.d(LOG_TAG, towns); try { townsObj = new JSONObject(towns); JSONArray townsArray = townsObj.getJSONArray("towns"); Log.d(LOG_TAG, townsArray.toString()); for (int i = 0; i < townsArray.length(); i++) { JSONObject obj = townsArray.getJSONObject(i); Log.d(LOG_TAG, "id: " + obj .getString("id")); Log.d(LOG_TAG, "name: " + obj .getString("name")); TOWNS_LIST.add(obj .getString("name")); } } catch (JSONException e) { e.printStackTrace(); } 

But I get this error:

 org.json.JSONException: Value {"name":"Berlin","id":1} at 0 of type java.lang.String cannot be converted to JSONObject 

Why it happens? what am I doing wrong?

    1 answer 1

    Every time I see a manual parsing Json line, the hand reaches for the gun, or rather Google Gson :

     public class Town { private String name; private int id; } Gson gson=new Gson(); Town[] towns=gson.fromJson(jsonString, Town[].class); 
    • if json really comes the same as in the question, then the problem is not so easy to solve. there is an array of strings - andreich
    • And what is the array? In my example, just an array and understands - Barmaley