motevalizadeh motevalizadeh - 3 months ago 17
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


or

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


What is wrong with this codes ?

Answer

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

https://developer.android.com/reference/org/json/JSONTokener.html