motevalizadeh motevalizadeh - 1 year ago 145
JSON Question

How to convert JSONTokener to JSONArray and JSONObject in android?

I want to cast a JSONTokener to JSONArray and JSONObject,
I know that is very simple and i did some search on but sample codes doesn't work for me,what is wrong?

StringBuilder builder= new StringBuilder();
//some codes to fill my StringBuilder

JSONTokener tokener = new JSONTokener( builder.toString() );

JSONArray finalResult = new JSONArray( tokener );
//error: Unhandle exeception:org.json.JsonExeception


JSONObject myJSONObject=new JSONObject(tokener)
//error: Unhandle exeception:org.json.JsonExeception

What is wrong with this codes ?

Answer Source

Don't try to create JSONObject from tokener. Simply cast its .nextValue().

From the official example:

 JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
 String query = object.getString("query");
 JSONArray locations = object.getJSONArray("locations");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download