【问题标题】:Android: string can't convert to JSONArray?Android:字符串无法转换为 JSONArray?
【发布时间】:2012-05-20 08:13:07
【问题描述】:

我可以从 php 的 json_encode 获得一个 json 响应,并且我能够在 eclipse 的 logcat 中显示响应是什么:

[{"idusers":"1","full_name":"Test Subject","get_email":"test_subject@gmail.com"},
{"idusers":"2","full_name":"Test Subject_2","get_email":"test_subject_2@gmail.com"}]

现在,我正在尝试

    //parse json data
    try {
        JSONArray jArray = new JSONArray(result);
        for(int i =0; i<jArray.length(); i++){
            JSONObject json_data = jArray.getJSONObject(i);
            Log.i("log_tag","id: "+json_data.getInt("idusers")+
                    ", Full Name: "+json_data.getString("full_name")+
                    ", Email: "+json_data.getString("get_email")
                    );
        }
    }catch(JSONException e){
        Log.e("log_tag","Error parsin data "+e.toString());
    }

但是,我收到一个错误提示

Error parsin data org.json.JSONException: Value testing of type java.lang.String cannot be converted to JSONArray

有没有办法解决 JSONArray 的问题?

提前致谢!

【问题讨论】:

标签: java android json http


【解决方案1】:

您的 JSON 无效。第二个数组元素的“get_email”值中缺少引号 (")。

应该是:

[
    {
        "idusers": "1",
        "full_name": "Test Subject",
        "get_email": "test_subject@gmail.com"
    },
    {
        "idusers": "2",
        "full_name": "Test Subject_2",
        "get_email": "test_subject_2@gmail.com"}]

【讨论】:

  • 这绝对是一个错字。因为我收到了来自 bufferreader 的响应
【解决方案2】:

发现发生了什么。我在 PHP 文档中有一个字符串并且没有被调用。我有“测试”这个词,这是错误中的词。一旦这个“测试”被删除,它就起作用了。谢谢

【讨论】:

    【解决方案3】:

    尝试向 JSON 返回的 PHP 变量添加强制转换。还有,你用的是json_encode吗?

    $user_id = (int) $id;
    $email = (string) $email;
    

    【讨论】:

    • 这是我在我的 PHP 文件while($get = $SQL-&gt;fetch(PDO::FETCH_ASSOC)){ $output[]=$get; } print(json_encode($output));中传递的内容@
    • 所以,从技术上讲,我并没有真正设置任何变量,它只是直接指向数组。 mysql中的数据类型是varchar,有区别吗?并且 id 是 int。
    猜你喜欢
    • 2017-06-04
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多