4

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

1
  • i still get this error: 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"} Commented Sep 7, 2011 at 11:13

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I still get this error: 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"}
An associative array will naturally be encoded as an object and not an array when converting to JSON.
@SJS The answer is in your reply... parse it as a JSON object and not a JSON array.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.