简体   繁体   中英

Java - how to parse both json arrays and objects

i am using the org.json package in Java (Android) and I am just stumbled with a simple problem.

The webserver returns an array if everything is okay, but an json object { error : true, ...} if something went wrong.

How can I parse that into a common object - I mean both arrays and objects are json after all, but it seems JSONArray and JSONOBject don't share an interface in common.

Am I missing something?

使用JSONTokener.nextValue()并检查结果是否为JSONObject或JSONArray(使用instanceof)。

The real answer is ... fix the webserver and have it return a consistant result. Otherwise, you basically are going to have to manually inspect the returned data to see what it is.

Another option is catching the JSONException the constructor for JSONArray will throw when it isn't an array which would indicate to you that you should try JSONObject .

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