Java Json-lib note
- JSON array: convert to Java JSONArray.
- JSONArray instance: convert to List.
- List: convert to Java JSONArray.
- JSONArray instance: convert to JSON array(String).
- ClassCastException.
- You can not use iterator() for enhanced for-loop.
JSON(string) array, Java List and Java JSONArray
-
JSON array: convert to Java JSONArray.
It thinks JSON string as a String object which formated by JSON. Therefore invoke JSONArray.fromObject(), return a JSONArray instance.
jsonArray = JSONArray.fromObject( "[1, 2, 3]" );
-
JSONArray instance: convert to List.
Invoke JSONArray.toCollection(), pass class of target. However, it is still an unchecked or unsafe operations.
List<Integer> idList; idList = (List<Integer>) JSONArray.toCollection(jsonArray, Integer.class);
-
List: convert to Java JSONArray.
jsonArray = JSONArray.fromObject( idList );
-
JSONArray instance: convert to JSON array(String).
System.out.println( jsonArray.toString() );
JSONArray iterator and exception.
-
ClassCastException.
Even you pass class to toCollection(), toCollection() won't throw this exception. It is only raised when you try to get an element from collection to variable.
-
You can not use iterator() for enhanced for-loop.
Method iterator() is not iterable by enhanced for-loop, because it fotgets to add interface Iterable into its implements list. It only lists JSON, List and Comparable.
public final class JSONArray extends Object implements JSON, List, Comparable
http://json-lib.sourceforge.net/apidocs/jdk15/net/sf/json/JSONArray.html
http://blogs.sun.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with