Ich versuche, ein Json-Objekt (oder ein Array zu lesen, ich bin mir nicht sicher, was zum Teufel das ist). Wie auch immer, ich möchte darauf hinweisen, dass ich gestern mit json Arrays gearbeitet habe.
Hier passiert was passiert:
//doesn’t work
JSONArray valarray = new JSONArray(result);
Gibt diesen Fehler: type org.json.JSONObject cannot be converted to JSONArray
//works
JSONObject jsonObject = new JSONObject(result);
Log.v("RESULTS" , jsonObject.get("results").toString());
//Doesn’t work
JSONObject jsonObject = new JSONObject(result);
JSONObject resultsObject = jsonObject.getJSONObject("results");
Gibt diesen Fehler: type org.json.JSONArray cannot be converted to JSONObject
Hier ist der JSON:
{
"html_attributions" : [],
"results" : [
{
"geometry" : {
"location" : {
"lat" : 50.6,
"lng" : -0.00
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "242c6a9664ca28a2",
"name" : "whatever",
"place_id" : "ChIJ6xum8T",
"reference" : "CoQBdQAAAIp",
"scope" : "GOOGLE",
"types" : [ "establishment" ],
"vicinity" : "United Kingdom"
}
],
"status" : "OK"
}
Wie soll ich das bekommen? lat
und lng
Innen geometry
zum Beispiel?
Antworten:
1 für die Antwort № 1Ihr JSON besteht aus einem object
. Das object
enthält ein Array mit dem Namen results
. Das Array enthält object
Elemente. Jeder object
im Array enthält ein object
genannt geometry
. Dieses Objekt enthält ein object
genannt location
. Das object
enthält lat
und lng
Gleitkommawerte.
Ihr Code sollte also ungefähr so aussehen:
String json = ...;
JSONObject JsonObj = new JSONObject(json);
JSONArray ResultArr = JsonObj.getJSONArray("result");
JSONObject ResultObj = ResultArr.getJSONObject(0);
JSONObject Geometry = ResultObj.getJSONObject("geometry");
JSONObject Location = Geometry.getJSONObject("location");
double Latitude = Location.getDouble("lat");
double Longitude = Location.getDouble("lng");
Da Sie es mit einem Array zu tun haben, können Sie es wie folgt durchlaufen:
String json = ...;
JSONObject JsonObj = new JSONObject(json);
JSONArray ResultArr = JsonObj.getJSONArray("result");
int count = ResultArr.length();
for (int i = 0; i < count; ++i)
{
JSONObject ResultObj = ResultArr.getJSONObject(i);
JSONObject Geometry = ResultObj.getJSONObject("geometry");
JSONObject Location = Geometry.getJSONObject("location");
double Latitude = Location.getDouble("lat");
double Longitude = Location.getDouble("lng");
//...
}