Gson核心类 创建: 1、Gson创建一个类 Gson gson = new Gson(); // Or use new GsonBuilder().create();
2、GsonBuilder创建一个可选的类
Gson gson = new GsonBuilder() .registerTypeAdapter(Id.class, new IdTypeAdapter()) .enableComplexMapKeySerialization() .serializeNulls() .setDateFormat(DateFormat.LONG) .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) .setPrettyPrinting() .setVersion(1.0) .create();
3、没有参数化的类型序列化和反序列化 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
4、有参数化的序列化和反序列化 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);
|
二、Gson反序列化: 1、类型一:JavaBean:Gson将json字符串转化成JavaBean对象
//这里将javabean转化成json字符串
Person person = new Person("香港","刘德华",1001);
String jsonString = gson.toJson(person);
//这里将json字符串转化成javabean对象,
Gson gson = new Gson();
person = gson.fromJson(jsonString,Person.class);
2、类型二:List<JavaBean>:将json字符串转化成List<JavaBean>对象
Person person1 = new Person("香港","刘德华",1001);
Person person2 = new Person("韩国","宋慧乔",1002);
List<Person> persons = new ArrayList<Person>();
persons.add(person1);
persons.add(person2);
//这里将lsit<javabean>转化成json字符串
String jsonString = gson.toJson(persons);
//解析json字符串
Gson gson = new Gson();
List<Person> persons2 = gson.fromJson(jsonString, new TypeToken<List<Person>>(){}.getType());
3、类型三:List<String>:将json字符串转化成List<String>对象
List<String> list = new ArrayList<String>();
list.add("gson1");
list.add("gson2");
list.add("gson3");
String jsonString = gson.toJson(list);
//解析json字符串
Gson gson = new Gson();
List<String> list2 = gson.fromJson(jsonString, new TypeToken<List<String>>(){}.getType()); 4、类型四:List<Map<String,Object>>:将json字符串转化成List<Map<String,Object>>对象
Map<String,Object> map = new HashMap<String,Object>();
map.put("key1", "value1");
map.put("key2", "value2");
Map<String,Object> map2 = new HashMap<String,Object>();
map2.put("key1", 1);
map2.put("key2", 2);
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
list.add(map);
list.add(map2);
Gson gson = new Gson();
String jsonString = gson.toJson(list);
//解析json字符串
List<Map<String,Object>> list2 = gson.fromJson(jsonString, new TypeToken<List<Map<String,Object>>>(){}.getType()); |