【问题标题】:Trying to return data from PHP with JSON to Android.....尝试使用 JSON 将 PHP 中的数据返回到 Android .....
【发布时间】:2023-04-02 11:48:01
【问题描述】:

尝试使用 JSON 将 PHP 中的数据返回到 Android。下面是我的php脚本

<?php 
#
print(json_encode("[name=john]"));
#
?>

但我在 java 中遇到错误:ERROR/log_tag(907): Error parsing data org.json.JSONException: A JSONArray text must start with '[' at character 0 of

【问题讨论】:

  • 我仍然收到此错误:09-07 07:12:28.309: ERROR/log_tag(907): Error parsing data org.json.JSONException: A JSONArray text must start with '[' at character 1 of {"name":"john"}

标签: java php android json


【解决方案1】:

json_encode 需要一个实际的对象或数组来编码为 json 格式。此外,最好为响应标头设置内容类型。试试这个:

<?php
    header('Content-type: application/json');
    print json_encode(array('name' => 'john'));
?>

我对 java 方面不太了解。正如nikc 所提到的,json_encode 将关联数组更改为 json 对象,将数值数组更改为 json 数组。

【讨论】:

  • 我仍然收到此错误:09-07 07:12:28.309: ERROR/log_tag(907): Error parsing data org.json.JSONException: A JSONArray text must start with '[' at character 1 of {"name":"john"}
  • 关联数组在转换为 JSON 时自然会被编码为对象而不是数组。
  • @SJS 答案在您的回复中...将其解析为 JSON 对象而不是 JSON 数组。
【解决方案2】:

您正在使用 json_encode 对 json 数组进行编码。在 json 中,[ ](方括号)代表数组,{ }(花括号)代表对象。使用 [enobrev] 给出的示例,返回一个 json 对象而不是 json 数组。

在这种情况下,您的解决方案是在 android 中调用

//Example of the content of result:
// {"name":"john"} This would be the result returned from the restfull request
// This the above JSON would be stored in a variable of type String.
JSONObject obj = new JSONObject(result); //JSONObject's constructor accepts a string as parameter

当你有了对象后,你就可以写了:

obj.getString("name");

这将检索键为“name”的值

其用法示例如下:

Toast.makeText(context, obj.getString("name"), Toast.LENGTH_LONG).show();

返回 john。

因为你得到的错误暗示你试图从一个 json 对象中创建一个 json 数组。

【讨论】:

    猜你喜欢
    • 2012-10-30
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多