1

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));
    }
  }
}
1
  • 1
    so what happen after try your code ? Commented Jan 11, 2013 at 6:55

3 Answers 3

1

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");

  ---------
}
Sign up to request clarification or add additional context in comments.

Comments

0

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");

...

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.