日期:2014-05-16 浏览次数:20345 次
public static void main(String[] args) { Gson gson = new Gson(); System.out.println(gson.toJson(1)); // ==> prints 1 System.out.println(gson.toJson("abcd"));// ==> prints "abcd" System.out.println(gson.toJson(new Long(10)));// ==> prints 10 int[] values = { 1 }; System.out.println(gson.toJson(values));// ==> prints [1] System.out.println("============"); int one = gson.fromJson("1", int.class); Integer one1 = gson.fromJson("1", Integer.class); Long one2 = gson.fromJson("1", Long.class); String str = gson.fromJson("\"abc\"", String.class); String anotherStr = gson.fromJson("[\"abc\"]", String.class); int[] ints = gson.fromJson("[1,2,3,4,5]", int[].class); Boolean b = gson.fromJson("false", Boolean.class); System.out.println(b == false); //==> prints true }
public class BagOfPrimitives { private int value1 = 1; private String value2 = "abc"; //是用于声明变量在序列化的时候不被存储 private transient int value3 = 3; BagOfPrimitives() { // no-args constructor } public static void main(String[] args) { BagOfPrimitives obj = new BagOfPrimitives(); Gson gson = new Gson(); String json = gson.toJson(obj); System.out.println(json); //==> json is {"value1":1,"value2":"abc"} BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class); System.out.println(obj2.value1); System.out.println(obj2.value2); System.out.println(obj2.value3);//==>3 String json1 = "{'value1':1,'value2':'abc','value3':4}"; BagOfPrimitives obj3 = gson.fromJson(json1, BagOfPrimitives.class); System.out.println(obj3.value1); System.out.println(obj3.value2); System.out.println(obj3.value3); //==>3 } }
String json1 = "{'value1':1,'value2':'abc','value3':4}"; JSONObject jsonObj = JSONObject.fromObject( json1 ); BagOfPrimitives obj3 = (BagOfPrimitives) JSONObject.toBean( jsonObj, BagOfPrimitives.class );