简体   繁体   English

尝试将带有JSON的PHP数据返回到Android ...

[英]Trying to return data from PHP with JSON to Android…

Trying to return data from PHP with JSON to Android. 尝试将带有JSON的PHP数据返回到Android。 below is my php script 下面是我的PHP脚本

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

But I am getting the error in java : ERROR/log_tag(907): Error parsing data org.json.JSONException: A JSONArray text must start with '[' at character 0 of 但是我在java中收到错误:ERROR / log_tag(907):解析数据时出错org.json.JSONException:JSONArray文本必须以'['在字符0处开头

json_encode needs an actual object or array to encode into json format. json_encode需要一个实际的对象或数组来编码为json格式。 Also, it's good practice to set the content type for the response header. 此外,最好为响应标头设置内容类型。 Try this: 试试这个:

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

I don't know much about the java side. 我不太了解java方面。 As nikc , mentioned, json_encode changes associative arrays to json objects and numerical arrays into json arrays. 正如nikc所提到的, json_encode将关联数组更改为json对象,将数值数组更改为json数组。

you are encoding a json array with json_encode. 你用json_encode编码一个json数组。 In json [ ](square brackets) stands for array and { }(curley brackets) for object. 在json [](方括号)中代表对象的数组和{}(curley括号)。 Using the sample given by [enobrev], returns a json object rather then json array. 使用[enobrev]给出的样本,返回一个json对象而不是json数组。

Your solution in this case would be in android to call 在这种情况下你的解决方案将在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

When you have the object you can then write: 当你有了对象时,你可以写:

obj.getString("name");

This will retrieve the value from which the key is "name" 这将检索密钥为“name”的值

An example of its usage can be: 它的用法示例可以是:

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

which returns john. 返回约翰。

Because the error you got implies that you are trying to make a json array out of a json object. 因为你得到的错误意味着你试图用json对象创建一个json数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM