I have this array in json code.

$info=array();
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
  array_push($info,$row);
}
$info;
$result_final->lugares_cercanos = $info;

Print this:

{"logstatus":"1","lugares_cercanos":[{"nombre":"Rio Amazonas","distancia":"5119.000"}{"nombre":"Swissotel Quito","distancia":"5823.000"}{"nombre":"Laguna de Yaguarcocha","distancia":"71797.000"}]}

Now, the problem is, How can I put the fields of "lugares_cercanos" into java ArrayList??

I try with this code:

{
  JSONArray jdata=post.getserverdata(postparameters2send, URL_connect);
  if (jdata!=null && jdata.length() > 0){
    JSONObject json_data;
    ArrayList<NameValuePair> lugares = new ArrayList<NameValuePair>();

    json_data = jdata.getJSONObject(0);
    logstatus=json_data.getInt("logstatus");                        
    lugaresCercanos=json_data.getJSONArray("lugares_cercanos");     

    for (int i = 0; i < lugaresCercanos.length(); ++i) {
      JSONObject rec = lugaresCercanos.getJSONObject(i);
      String name = rec.getString("nombre");
      String dist = rec.getString("distancia");
      lugares.add(new BasicNameValuePair(name,dist));
    }
  }
}
share|improve this question
1  
so what happen after try your code ? – Jason Jan 11 at 6:55
show this error: – user1957012 Jan 13 at 7:01
feedback

3 Answers

show this error:

Error parsing data org.json.JSONException: Value {"lugares_cercanos":[{"nombre":"Laguna de Yaguarcocha","distancia":"8686205.000"},{"nombre":"Swissotel Quito","distancia":"8728811.000"},{"nombre":"Rio Amazonas","distancia":"8729333.000"}],"logstatus":"1"} of type org.json.JSONObject cannot be converted to JSONArray

share|improve this answer
feedback

Try this:

JSONObject j = jdata.getJSONObject("obj");
JSONArray jArray = j.getJSONArray("lugares_cercanos");
int len = jArray .length(); 
for(int i=0; i <len; i++){
  String nombre = jArray .getJSONObject(i).optString("nombre");

  ---------
}
share|improve this answer
feedback

The top level structure (i.e. the JSON string you have posted) is not an array but an object.

I don't know what your post.getserverdata method does, if there is a version that can return a JSONObject you could use:

JSONObject jdata=post.getserverdataobject(postparameters2send, URL_connect);
logstatus=jdata.getInt("logstatus");
lugaresCercanos=jdata.getJSONArray("lugares_cercanos");

...
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.