?
使用gson的tojson和fromjson實現對象和json的轉換
Gson gson = new Gson(); // Or use new GsonBuilder().create();
?? ? MyType target = new MyType();
?? ? String json = gson.toJson(target); // serializes target to Json
?? ? MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
?
?Type listType = new TypeToken<List<String>>() {}.getType();
???? List<String> target = new LinkedList<String>();
???? target.add("blah");
???? Gson gson = new Gson();
???? String json = gson.toJson(target, listType);
???? List<String> target2 = gson.fromJson(json, listType);
?
?使用GsonBuilder創建gson對象
??? ? Gson gson = new GsonBuilder()
??? ??? ?.registerTypeAdapter(Id.class, new IdTypeAdapter())
??? ??? ?.enableComplexMapKeySerialization()
??? ??? ?.serializeNulls()
??? ??? ?.setDateFormat(DateFormat.LONG)
??? ??? ?.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
??? ??? ?.setPrettyPrinting()
??? ??? ?.setVersion(1.0)
??? ??? ?.create();
?
??? ??? ?? Gson gson = new GsonBuilder()
?????? .register(Point.class, new MyPointTypeAdapter())
?????? .enableComplexMapKeySerialization()
?????? .create();
?
map對象轉換成json對象
? Gson gson = new GsonBuilder()
?????? .register(Point.class, new MyPointTypeAdapter())
?????? .enableComplexMapKeySerialization()
?????? .create();
?? Map<Point, String> original = new LinkedHashMap<Point, String>();
?? original.put(new Point(5, 6), "a");
?? original.put(new Point(8, 8), "b");
?? System.out.println(gson.toJson(original, type));
?
?? ?The above code prints this JSON object:
? {
???? "(5,6)": "a",
???? "(8,8)": "b"
?? }
?map對象轉化成jsonArray對象:
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();Map<Point, String> original = new LinkedHashMap<Point, String>();original.put(new Point(5, 6), "a");original.put(new Point(8, 8), "b");System.out.println(gson.toJson(original, type));
The JSON output would look as follows:
[[{"x": 5,"y": 6},"a"],[{"x": 8,"y": 8},"b"]]
JsonParser
parse方法將json類型的字符串,或者reader對象或者JsonReader對象解析成為jsonElement對象
?