使用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(); Maporiginal = new LinkedHashMap (); 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对象