ThemuRR ThemuRR - 6 months ago 13
PHP Question

How do I parse this PHP to Java using JSON?

I am pulling my hair out over this. I still don't fully understand how JSON works. I am trying to return a number (formatted as a string) from a PHP script to java. I keep getting the following error:

Error parsing data org.json.JSONException: Value http of type java.lang.String cannot be converted to JSONArray


This is a snippet from the PHP code:

class result
{
public $value = "";
}

$result = new result();
$result->value = "1";

print(json_encode($result));


This returns:
{"value":"1"}

I am trying to store the '1' in a string for error checking purposes on the android side.

It inserts into MySQL database first and that works but it wont return the value correctly.

Here is the java code I have been attempting to use:

try
{
CustomHttpClient.executeHttpPost(response="http://test.com/test.php",postParameters);

String result = response.toString();

try
{
returnString = "";

JSONArray jArray = new JSONArray(result);

for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","value:"+json_data.getString("value"));

returnString = json_data.getString("value");

}

}

catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "Error Parsing", Toast.LENGTH_LONG).show();
}
}

Answer

Your PHP code returns a JSON object (enclosed in {}), not an array (enclosed in []). So, you need to change your JSON parsing code as

returnString = "";

JSONObject json_data = new JSONObject(result);
Log.i("log_tag","value:"+json_data.getString("value"));

returnString = json_data.getString("value");

Since, there's only one JSON object being returned, there's no need of the loop too.