J'essaie de lire un objet JSON (ou un tableau, tbh je ne suis pas sûr de ce que c'est.) Quoi qu'il en soit, je tiens à souligner que j'ai commencé à travailler avec les tableaux JSON hier, donc je suis désolé si cette question est simple.
Voici ce qui se passe:
//doesn’t work
JSONArray valarray = new JSONArray(result);
Donne cette erreur: 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");
Donne cette erreur: type org.json.JSONArray cannot be converted to JSONObject
Voici le 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"
}
Comment suis-je supposé obtenir le lat
et lng
à l'intérieur de geometry
par exemple?
Réponses:
1 pour la réponse № 1Votre JSON consiste en un object
. Cette object
contient un tableau nommé results
. Le tableau contient object
éléments. Chaque object
dans le tableau contient un object
nommé geometry
. Cet objet contient un object
nommé location
. Cette object
contient lat
et lng
valeurs en virgule flottante.
Donc, votre code devrait ressembler à ceci:
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");
Puisque vous avez affaire à un tableau, vous pouvez le parcourir comme ceci:
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");
//...
}