Android的,的JSONObject不能转换为JSONArray [英] Android, JSONObject cannot be converted to JSONArray

查看:234
本文介绍了Android的,的JSONObject不能转换为JSONArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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),其中,

        回声 '}'

    ?>
 

我称之为的.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");
...

这篇关于Android的,的JSONObject不能转换为JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆