简体   繁体   中英

Trying to return data from PHP with JSON to Android…

Trying to return data from PHP with JSON to Android. below is my php script

<?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

json_encode needs an actual object or array to encode into json format. 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. As nikc , mentioned, json_encode changes associative arrays to json objects and numerical arrays into json arrays.

you are encoding a json array with json_encode. In json [ ](square brackets) stands for array and { }(curley brackets) for object. Using the sample given by [enobrev], returns a json object rather then json array.

Your solution in this case would be in android to call

//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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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