简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM