0

Im writing a client/server app for android that sends a username and password to the server and receives a status for that user account.

My php code is like this:

$return['login'] = 'success';   
echo json_encode($return);

and the text received by android is:

{"login":"success"}

but I still get an error when I try to decode the json string to read the parameters:

JSONArray jsonArray = new JSONArray(input);

exception:

02-10 11:54:37.743: WARN/System.err(332): 
    org.json.JSONException: 
         Value {"login":"success"} of type org.json.JSONObject 
         cannot be converted to JSONArray
02-10 11:54:37.779: WARN/System.err(332): 
    at org.json.JSON.typeMismatch(JSON.java:107)

So I guess Im missing something that php should send, but after reading on json.org I just can't see what it is. I have tried adding brackets before and after, as well as wrapping it in another array like this:

$parameters['login'] = 'success';   
    $return['parameters'] = $parameters;
echo json_encode($return);
2
  • probably because it is not a json array… Commented Feb 10, 2012 at 11:07
  • The exception seems obvious but I think there is a misunderstanding because PHP Arrays are just ordered maps. Commented Feb 10, 2012 at 11:29

3 Answers 3

2

You should be using JSONObject instead of JSONArray since you sending a key-value pair.

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

1 Comment

That explains it, in my head I was under the impression that several key-value-pairs would be an array.
1

Its an JSONObject not an JSONArray so it should be,

JSONObject json_obj = new JSONObject(your_string);

Then you can just use json_obj to get the value,

String login = json_obj.getString("login");
Log.d("login status", login);

Comments

0

Your json is not a JSONArray, it is a JSONObject.

try {
    JSONObject o = new JSONObject("{\"login\":\"success\"}");
    System.out.println(o.getString("login"));
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Output:

System.out  I  success

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.