日期:2014-05-16 浏览次数:20506 次
Model.java private String title; private int num; private Integer sort; private Date date; private String[] strArray; private SubModel subModel; SubModel.java private String name; Marshal 實作 Object2JSON.java import java.util.Date; import net.sf.json.JSONObject; public class Object2JSON { public static void main(String[] args) { //產生Model Model 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); //轉換為JSON String json = JSONObject.fromObject(model).toString(); //顯示XML System.out.println(json); } } Unmarshal 實作 JSON2Object.java import 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\"}"; //轉換JavaBean Model 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 結論