最近更新: 2009-12-21

Java Json-lib note

  1. JSON array: convert to Java JSONArray.
  2. JSONArray instance: convert to List.
  3. List: convert to Java JSONArray.
  4. JSONArray instance: convert to JSON array(String).
  5. ClassCastException.
  6. You can not use iterator() for enhanced for-loop.

JSON(string) array, Java List and Java JSONArray

  1. 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]" );
  2. 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);
  3. List: convert to Java JSONArray.
    jsonArray = JSONArray.fromObject( idList );
  4. 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

樂多舊網址: http://blog.roodo.com/rocksaying/archives/11126901.html