2016-05-02 6 views
1

Ich bin JSON Zeichenfolge in URL analysieren.Android String zu JSON Array Fehler

TextView tv3 = (TextView) findViewById(R.id.tv3); 
TextView tv2 = (TextView) findViewById(R.id.tv2); 
TextView tv1 = (TextView) findViewById(R.id.tv1); 

String str = "[{\"ID\":\"1\",\"lat\":\"40.7646815\",\"lon\":\"29.030855\"},{\"ID\":\"2\",\"lat\":\"41.10812\",\"lon\":\"29.030855\"}]"; 


JSONArray jsonarray = null; 
try { 

    jsonarray = new JSONArray(str); 
    for (int i = 0; i < jsonarray.length(); i++) { 
     JSONObject obj = jsonarray.getJSONObject(i); 

     String lat = obj.getString("lat"); 
     String lon = obj.getString("lon"); 
     String id = obj.getString("ID"); 

     tv3.setText(lat); 
     tv2.setText(lon); 
     tv1.setText(ID); 
    } 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

Ich möchte Umwandlung JSONArray-Stringaber JSONArray Rückkehr leer. Wo bin ich Fehler? Danke ..

+0

@prudhvi wissen Sie nicht, wie zitiert in Java-Strings zu entkommen? – njzk2

+0

irgendeine Ausnahme überhaupt? – njzk2

Antwort

0

versuchen diese

jsonarray = new JSONArray(str.replace("\\\"", "\"").replace("\n","").replaceAll("^\"|\"$", "").trim()); 
+0

Vielen Dank. Es ist sehr gut. –

+0

Sie sind willkommen –

-1

Try this:

JSONArray arrayObj = null; 
JSONParser jsonParser = new JSONParser(); 
object = jsonParser.parse(str); 
arrayObj = (JSONArray) object; 
+0

Woher kommt die Klasse 'JSONParser'? – njzk2

0

Verwenden JSONObject und JSONArray Klassen JSONArray zu konstruieren, statt es als String zu schreiben.

Siehe https://stackoverflow.com/a/17810270/4586742

+0

Die JSON-Zeichenfolge kommt von einer URL, wenn ich die Frage richtig verstehe. –