Android的,的JSONObject不能转换为JSONArray转换为、Android、JSONObject、JSONArray

2023-09-04 04:00:42 作者:無樂不歡

在我的Andr​​oid应用程序,我想与保存随机生成假的用户名和得分的Web服务器进行通信。

  {分数:
 {
联合国:Feltricapulta
SC:143
},
{
联合国:Henroid
SC:120
},
{
联合国:ieteubmospta
SC:70
},
{
联合国:pmbotesteuai
SC:67
},
{
联合国:epesomiubtat
SC:65
}
]}
 

在code在PHP文件看起来是这样的:

 < PHP

    包括('connecttomysql.php');


    $命令='选择取消,SC从xmlscores ORDER BY SC DESC';
    $ execute_command =请求mysql_query($命令);

        回声{算账:;

    而($ table_row = mysql_fetch_assoc($ execute_command))
        {
            $ jsonArray [] = $ table_row;
        }
        回声json_en code($ JSONArray),其中,

        回声 '}'

    ?>
 
如何完成Goods查询页面 使用Map进行键值对的传入来编写规格参数,StringUtils的分割符用法,json对象的序列化和反序列化,

我称之为的.php URL在Android中使用通用 HTTPGET 方法。 JSON数据打印到堆栈跟踪的输出,并为我提供了无法转换对象为阵的错误。

纵观PHP文件和JSON输出,有什么明显的毛病我codeS或输出?我不明白。

解决方案   

不能从对象转换为阵

意味着你正试图响应字符串转换为 JSONArray 。但当前字符串包含的JSONObject 的根元素,而不是 JSONArray 。所以它转换成的JSONObject 为:

 的JSONObject JSON =新的JSONObject(小于这里和服务器响应字符串GT;);

//从JSON获得的分数JSONArray
JSONArray jsonscoresarray = json.getJSONArray(分);
...
 

In my Android app, I'm trying to communicate with a web server that holds randomly-generated fake usernames and scores.

{ scores: [
 {
un: "Feltricapulta",
sc: "143"
},
{
un: "Henroid",
sc: "120"
},
{
un: "ieteubmospta",
sc: "70"
},
{
un: "pmbotesteuai",
sc: "67"
},
{
un: "epesomiubtat",
sc: "65"
}
] }

The code in the PHP file looks like this:

<?php 

    include ('connecttomysql.php');


    $command = 'SELECT un, sc FROM xmlscores ORDER BY sc DESC';
    $execute_command = mysql_query($command);

        echo '{ "scores": ';

    while ($table_row = mysql_fetch_assoc($execute_command))
        {
            $jsonArray [] = $table_row;         
        }
        echo json_encode($jsonArray);

        echo '}'

    ?>

I've called this .php URL in Android using the generic HttpGet method. The output of the json data prints to the stacktrace and provides me with the "Cannot convert from Object to Array" error.

Looking at the PHP file and the json output, is there anything noticeably wrong with my codes or the output? I can't figure it out.

解决方案

"Cannot convert from Object to Array"

means you are trying to convert response string to JSONArray. but Current String Contains JSONObject as root element instead of JSONArray. so convert it to JSONObject as:

JSONObject json=new JSONObject(<Server response string here>);

//  get scores JSONArray from json
JSONArray jsonscoresarray=json.getJSONArray("scores");
...