java - 如何在android中检索json数组?

标签 java android json

下面是我的 Android 代码,它应该检索 json 数组。但它显示“json数组无法转换为json对象”的异常。这段代码有什么问题?

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 文件

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

下面是我的 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"}]

最佳答案

您应该检查 JSON 作为字符串以了解问题出在哪里,无论如何,如果结果是 JSON 数组(如 [ .... ] ),您的第一行就是错误的

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

应该是

JSONArray jArray = json.getJSONArray(result);

但为了确保你应该发布你的 JSON 字符串...

还有另一种想法让我有点困惑,在 JAVA 中,JSONObject 是围绕 HashMap 创建的(如您所见 here ) JSONArray 非常接近 HashMap 数组...

我认为你想做的事情有点没用......

关于java - 如何在android中检索json数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33013187/

相关文章:

java - 在没有源代码的情况下序列化为 JSON 时更改属性名称

ios - 使用嵌套对象和键为数组建模

Java 启动但返回退出代码 13

Java字符串用数组中的新模式替换正则表达式

java - 添加/修改 Tomcat 库

java - 如果在android中找不到元素如何抛出

javascript - 变量在运行时未定义,但在使用调试器时定义

java - 在Java中解析长数字

android - 使用 Mailgun API 通过电子邮件发送 otp

android - 如何在模拟器 Android 上测试具有不同版本代码和小数据库更改的 apk