【问题标题】:Android retrieve data from php org.json.JSONArray cannot be converted to JSONObjectAndroid 从 php org.json.JSONArray 检索数据无法转换为 JSONObject
【发布时间】:2016-02-26 12:39:58
【问题描述】:

我正在尝试从 php 服务器获取一组数据到 android。 但是当我执行项目时发生错误,尝试参考几个相关问题但我仍然无法提出解决方案。

这是我的异步任务,它将建立连接并将 momentID 发送到 php

class GetAllComment extends AsyncTask<String, String, ArrayList<Comment>> {


    protected ArrayList<Comment> doInBackground(String... params) {
                    List<NameValuePair> param = new ArrayList<NameValuePair>();
                    int success;
        try {
            Log.d("","@@@### " + postedID);
            param.add(new BasicNameValuePair("momentid", postedID));
            JSONObject json = jsonParser.makeHttpRequest(
                    "http://192.168.168.111:80/testmoment/getallcomment.php", "GET", param);

            // check your log for json response
            Log.d("Single comments Details", json.toString());

            // json success tag
            success = json.getInt("success");
            if (success == 1) {

                JSONArray productObj = json
                        .getJSONArray("product"); // JSON Array


                try {
                    JSONObject comments = productObj.getJSONObject(0);
                    Comment comment = new Comment();
                    comment.setCommentContentbody(comments.getString("vcontentbody"));
                    comment.setCommentDate(comments.getString("vcdate"));
                    comment.setCommentTime(comments.getString("vctime"));
                    list.add(comment);

                    Log.d("","tryget : " + comments.getString("vcid") + " AND " + comments.getString("vcontentbody") + " AND " + comments.getString("vcdate") + " AND " + comments.getString("vctime"));

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else {

            }
        }catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    protected void onPostExecute(ArrayList<Comment> list) {
        cAdapter = new CommentAdapter(getActivity().getBaseContext(), mCommentLists);
        commentList.setAdapter(cAdapter);
        mComment = new Comment();
        cAdapter.Update();

        if(list != null){
            for(Comment comment: list){
                cAdapter.add(comment);
            }
        }


        cAdapter.notifyDataSetChanged();
    }
}

这是我的 php 脚本:

<?php

header('Content-type: application/json');
include "db.config.php";
if (isset($_GET['momentid'])){
$momentid = $_GET['momentid'];
$result =mysql_query("SELECT * FROM commenttable WHERE vcmomentid = $momentid");

if (!empty($result)) {
    // check for empty result
    while($row=mysql_fetch_assoc($result))
        $json_output[]=$row;

print(json_encode($json_output));

mysql_close();
        echo json_encode($response);
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No product found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // no product found
    $response["success"] = 0;
    $response["message"] = "No product found";

    // echo no users JSON
    echo json_encode($response);
}

?>

这是我执行后得到的错误:

JSON Parser: Error parsing data org.json.JSONException: Value [{"vcontentbody":"gkkgv","vcid":"1","vcmomentid":"109","vcdate":"2015-11-23","vcuserid":"1578","vctime":"17:09 PM"}] of type org.json.JSONArray cannot be converted to JSONObject

请帮我找出错误。谢谢

【问题讨论】:

  • 您的数据是以 JSON 数组类型而不是 JSON 对象类型检索的。所以在 JSON 数组而不是 JSON 对象中获取数据
  • 如日志of type org.json.JSONArray cannot be converted to JSONObject
  • 发布您的Json 数据。
  • 请编辑代码?我知道我的数据是在 JsonArray 而不是 Jsonobject 中检索的,但我的问题是如何将 Jsonobject 更改为 JsonArray?

标签: php android json


【解决方案1】:

实际上,您正在将 JSONArray 转换为 JSONObject

[ // This is Array
    { // This is Object
    "vcontentbody":"gkkgv",
    "vcid":"1",
    "vcmomentid":"109",
    "vcdate":"2015-11-23",
    "vcuserid":"1578",
    "vctime":"17:09 PM"
    }
]

所以你必须这样写:

JSONArray jsonArray = jsonParser.makeHttpRequest("http://192.168.168.111:80/testmoment/getallcomment.php", "GET", param);

现在检查它是否为null

if(jsonArray != null)
{
    // Here You may not have any key like 'success' so i don't have taken.

    // You can directly get JSON Object here.. If you are getting more than one JSONObject then make loop here...
    JSONObject object = jsonArray.getJSONObject(0);

    // Now you can do with object that you want to do.
    Comment comment = new Comment();
    comment.setCommentContentbody(object.getString("vcontentbody"));
    comment.setCommentDate(object.getString("vcdate"));
    comment.setCommentTime(object.getString("vctime"));
    list.add(comment);
}

如果有任何问题,您可以 ping 我。愿它对你有所帮助。谢谢。

【讨论】:

    【解决方案2】:

    这是您可以解析数据的代码,请将您的 jsonArray 放入响应变量中

    try {
            JSONArray arr=new JSONArray(response);
    
            JSONObject jobj=new JSONObject(arr.get(0).toString());
    
            for(int i=0;i<jobj.length();i++)
            {
               Log.e("Index 0", ":"+jobj.getString("vcontentbody")) ;
               Log.e("Index 1", ":"+jobj.getString("vcid"));
               Log.e("Index 2", ":"+jobj.getString("vcmomentid")) ;
               Log.e("Index 3", ":"+jobj.getString("vcuserid")) ;
               Log.e("Index 4", ":"+jobj.getString("vcdate")) ;
               Log.e("Index 4", ":"+jobj.getString("vctime")) ;
            }
    
    
        } catch (JSONException e) {
            e.printStackTrace();
        }
    

    【讨论】:

    • 我不擅长解析 json 我只是想问你你正在使用 arr.get(0) 那到底是什么
    • 我们这样做是为了获得第一名
    • 我这样做是为了获得第一个数组
    猜你喜欢
    • 2013-06-30
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2014-02-03
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多