motevalizadeh motevalizadeh - 7 months ago 50
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 ?


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");