adrian
adrian

Reputation: 4594

Obtain string from JSON Object

I have to following response from a server: page:{"result":"ok","id_photo":36782710}.And I'm trying to obtain the result from there by doing this:

String r=page.toString();
JSONArray jArray = new JSONArray(r);
JSONObject jsdata = r.getJSONObject(0);

String result = jsdata.getString("result");
System.out.println("Raspunsul de la server este:" +result);

But I get the following error:

WARN/System.err(30452): org.json.JSONException: Value {"result":"ok","id_photo":36782710} of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:107)
at org.json.JSONArray.<init>(JSONArray.java:91)
at org.json.JSONArray.<init>(JSONArray.java:103)
at com.Contest.DialogExampleActivity.executeMultiPartPost(DialogExampleActivity.java:131)
at com.Contest.DialogExampleActivity.btnSend_onClick(DialogExampleActivity.java:88)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at android.view.View$1.onClick(View.java:2157)
at android.view.View.performClick(View.java:2534)
at android.view.View$PerformClick.run(View.java:9210)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
at dalvik.system.NativeStart.main(Native Method

Anyone any idea?

Upvotes: 0

Views: 1261

Answers (3)

ayublin
ayublin

Reputation: 1845

As madsleejensen said, it should be treated as JSONObject not JSONArray, and for future references, simple advice to differ when to use the right type is: JSONObject is covered by {} and JSONArray covered by [].

Upvotes: 2

Mads Lee Jensen
Mads Lee Jensen

Reputation: 4658

Try instantiating it as a JSONObject instead as the data your a parsing is not an array but a object.

JSONObject json = new JSONObject(response);
String result = json.getString("result");

Upvotes: 3

Related Questions