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();
}
}
-
1well do you mean you want to pass json using php to java?Pankaj Nimgade– Pankaj Nimgade2015年02月25日 13:38:28 +00:00Commented Feb 25, 2015 at 13:38
-
1you´re trying to read an array but it´s a single object.eduyayo– eduyayo2015年02月25日 13:45:31 +00:00Commented Feb 25, 2015 at 13:45
3 Answers 3
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.
Comments
First of all I ́d recomend you to use Gson API which is an amazing API for handling JSON objects. I ́d strongly recomend you to read the guides at their website.
The problem here is that you ́re trying to convert an object into an array and that ́s why you ́re getting an Exception. The correct way to convert the value you specified above is:
JsonObject jObject = (JsonObject) new JsonParser().parse(value);
The example above is using Gson API but the same applies to your API.
Comments
You can try with this example, this is work for me:
public String listOfUser() {
//User users = new User();
String URI = "http://localhost/Perumahan/index.php/User_c";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
List<LinkedHashMap> users = restTemplate.getForObject(URI, List.class);
//userService.addUser(users);
return gson.toJson(users);
}