Genadinik
Genadinik

Reputation: 18649

Java JSON parsing exception after creating JSON in PHP on the server

I have this string that gets passed from the server:

{\"error\":\"email_in_diff_account\"}

It is created in PHP like this:

$post_data = array('error' => "email_in_diff_account");

echo json_encode($post_data);

But when I try to parse it like this in JAVA:

JSONArray obj = new JSONArray(result);

It causes the following exception.

org.json.JSONObject cannot be converted to JSONArray

Would anyone know how to fix this? Am I not creating the JSON correctly in php?

Upvotes: 0

Views: 114

Answers (4)

romualdr
romualdr

Reputation: 184

The correct use is: JSONObject json = new JSONObject(result);

Upvotes: 1

Ruan Mendes
Ruan Mendes

Reputation: 92314

If you're using http://www.json.org/javadoc/org/json/JSONArray.html

You are trying to parse an array but you are passing it an object, you should use http://www.json.org/javadoc/org/json/JSONObject.html

JSONObject json = new JSONObject(result);

Upvotes: 2

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

First of all this code can't create json like this

$post_data = array('error' => "email_in_diff_account");
echo json_encode($post_data);

{\"error\":\"email_in_diff_account\"}   // your output

{"error":"email_in_diff_account"}   // actual output

you can validate yor JSON using this link http://jsonlint.com/

see the working example of your code http://codepad.org/oJXj0GdI

Upvotes: 1

Someguynamedpie
Someguynamedpie

Reputation: 170

If those backslashes are there, that would be your issue. Please post the exception though.

Upvotes: 2

Related Questions