转载JSON Format(二)
转载http://blog.toright.com/?p=397
JSON Format
JSON量的料表示格式,比起 XML 散多且不需要定描述,JSON站 http://json.org/
Json-lib API
Json-lib 在多理 Jsob Format API 中作功能比多的一套件,可由下列址取得。
http://json-lib.sourceforge.net/ 此外,Json-lib需要以下 Library
jakarta commons-lang 2.4
jakarta commons-beanutils 1.7.0
jakarta commons-collections 3.2
jakarta commons-logging 1.1.1
ezmorph 1.0.6
JSON POJO 作
Model
Model.javaprivate String title;private int num;private Integer sort;private Date date;private String[] strArray;private SubModel subModel;SubModel.javaprivate String name;Marshal 作Object2JSON.javaimport java.util.Date;import net.sf.json.JSONObject;public class Object2JSON {public static void main(String[] args) {//生ModelModel model = new Model();model.setTitle("Master MOdel");model.setNum(99);model.setSort(10);model.setDate(new Date());model.setStrArray(new String[]{"str1","str2"});SubModel subModel = new SubModel();subModel.setName("MySubModel");model.setSubModel(subModel);//JSONString json = JSONObject.fromObject(model).toString();//示XMLSystem.out.println(json);}}Unmarshal 作JSON2Object.javaimport net.sf.json.JSONObject;public class JSON2Object {public static void main(String[] args) {String json = "{\"date\":{\"date\":27,\"day\":2,\"hours\":15,\"minutes\":30,\"month\":9,\"seconds\":35,\"time\":1256628635421,\"timezoneOffset\":-480,\"year\":109},\"num\":99,\"sort\":10,\"strArray\":[\"str1\",\"str2\"],\"subModel\":{\"name\":\"MySubModel\"},\"title\":\"Master MOdel\"}";//JavaBeanModel model = (Model)JSONObject.toBean( JSONObject.fromObject( json ), Model.class );//示容System.out.println("Title:"+model.getTitle());System.out.println("Num:"+model.getNum());System.out.println("Sort:"+model.getSort());System.out.println("Date:"+model.getDate());System.out.println("SubModel:"+model.getSubModel());System.out.println("SubModel[Name]:"+model.getSubModel().getName());}}Json-lib
之後 Json Array 是支援的,但是於 List Hashtable 的 Unmarshal 是不支援。假 Json 未成 Web Service 重要的格式,那作 Json 更高的 Unmarshal 是必要的工作。