简体   繁体   中英

String to JSONObject in Android raise exception

Here is the JSON format in String object which i am trying to convert into JSONObject in android.

{  
   "city":[  
      {  
         "id":"1",
         "name":"Mumbai"
      },
      {  
         "id":"2",
         "name":"Delhi"
      },
      {  
         "id":"3",
         "name":"Chennai"
      },
      {  
         "id":"4",
         "name":"Kolkatta"
      }
   ],
   "locality":[  
      {  
         "id":"1",
         "locality_city_id":"1",
         "locality_name":"Andheri"
      },
      {  
         "id":"2",
         "locality_city_id":"1",
         "locality_name":"Bandra"
      },
      {  
         "id":"3",
         "locality_city_id":"1",
         "locality_name":"Dadar"
      },
      {  
         "id":"4",
         "locality_city_id":"1",
         "locality_name":"Thane"
      }
   ],
   "diseases":[  
      {  
         "id":"1",
         "disease_name":"Blood Pressure"
      },
      {  
         "id":"2",
         "disease_name":"Diebetes"
      },
      {  
         "id":"3",
         "disease_name":"Hypertention"
      },
      {  
         "id":"4",
         "disease_name":"Dyslexia"
      }
   ]
}

I copied it to JSON beautifier and it says it is a valid JSON. But this raises exception. Is there anything wrong in the JSON format ?

Code used is:

JSONObject jsonObject = new JSONObject(jsonString);

Exception stacktrace:

08-11 11:22:33.548: W/System.err(3055): org.json.JSONException: Value {"city":[{"id":"1","name":"Mumbai"},{"id":"2","name":"Delhi"},{"id":"3","name":"Chennai"},{"id":"4","name":"Kolkatta"}],"locality":[{"id":"1","locality_city_id":"1","locality_name":"Andheri"},{"id":"2","locality_city_id":"1","locality_name":"Bandra"},{"id":"3","locality_city_id":"1","locality_name":"Dadar"},{"id":"4","locality_city_id":"1","locality_name":"Thane"}],"diseases":[{"id":"1","disease_name":"Blood Pressure"},{"id":"2","disease_name":"Diebetes"},{"id":"3","disease_name":"Hypertention"},{"id":"4","disease_name":"Dyslexia"}]} of type java.lang.String cannot be converted to JSONObject 08-11 11:22:33.548: W/System.err(3055): at org.json.JSON.typeMismatch(JSON.java:111) 08-11 11:22:33.548: W/System.err(3055): at org.json.JSONObject.(JSONObject.java:158) 08-11 11:22:33.548: W/System.err(3055): at org.json.JSONObject.(JSONObject.java:171)

I've tried with your JSON and the following code snippet works for me.

String strJson = YOUR_JSON_STRING_HERE;
try {
    JSONObject json = new JSONObject(strJson);
    System.out.println(json);
} catch (JSONException e) {
    e.printStackTrace();
}

Paste the whole code, because what ever you've provided works fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM