简体   繁体   English

如何在Android中检索json数组?

[英]How to retrieve the json array in android?

Below is my Android code which is supposed to retrieve the json array. 以下是我的Android代码,该代码应检索json数组。 But it shows an exception that "json array cannot be converted to json object". 但是它显示了一个例外,即“无法将json数组转换为json对象”。 What is wrong with this code? 此代码有什么问题?

JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("emparray");

ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

// testing works ...

// ... until here
for (int i = 0; i < jArray.length(); i++) {
    json = jArray.getJSONObject(i);

    String id = null, loc = null;
    id = json.getString("user_id");

    loc = json.getString("crtloc_lat");

    HashMap<String,String> persons2 = new HashMap<String,String>();
    persons2.put("uder_id",id);
    persons2.put("crtloc_lat",loc);
    personList.add(persons2);
    mylist.add(persons2);
    Toast.makeText(MapsActivity.this, "waw id is"+id, Toast.LENGTH_SHORT).show();
}

PHP file PHP文件

 <?php
require "config.php";
$con = mysqli_connect(HOST,USER,PASS,DB);

$pro_id=2;
$sql="SELECT user.user_id, current_location.crtloc_lat,current_location.crtloc_lng FROM user INNER JOIN current_location 
where user.user_id=current_location.user_id AND user.pro_id='$pro_id'";



  $result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));

    //create an array
    $emparray[] = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);

    //close the db connection
    mysqli_close($con);
?>

and the following is my json array 以下是我的json数组

[[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769547","crtloc_lng":"72.361504"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"},{"user_id":"86","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}]

You should check your JSON as string to understand where is the problem, in any case if result is a JSON Array (like [ .... ] ) your first line is wrong 您应该将JSON作为字符串进行检查,以了解问题出在哪里,无论如何,如果结果是JSON数组(例如[....]),则第一行是错误的

JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("emparray");

It should be 它应该是

JSONArray jArray = json.getJSONArray(result);

But to be sure you should post your JSON string... 但是请确保您应该发布JSON字符串...

There are also another think that makes me a little bit confused, in JAVA a JSONObject is created around an HashMap (as you can see here ) and a JSONArray is very close to an Array of HashMap ... 还有一种想法让我有些困惑, 在JAVA中,围绕HashMap创建了JSONObject (如您在此处看到的),而JSONArray与HashMap的数组非常接近 ...

I think that what are you tring to do is a bit useless... 我认为您打算做什么是没有用的...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM