gson支持解析的类型还是比较全面的,包括JavaBean,List<JavaBean>,List<String>,Map等,使用起来也是比较方便,下面根据代码示例给出总结:
package com.oyy.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* gson支持解析的类型还是比较全面的,包括JavaBean,List<JavaBean>,List<String>,Map等,使用起来也是比较方便.
* @author ouyangyu
* @date 2017-5-8 下午03:05:00
* @version V1.0
*/
public class T3 {
public static void main(String[] args) {
Gson gson = new Gson();
//将对象转换为json字符串
Person person = new Person();
person.setId(1);
person.setName("zhanglu");
person.setAddress("湖北大悟");
String jsonStr = gson.toJson(person);
System.out.println("将对象转换为json字符串的结果:"+jsonStr);
//将json字符串转换为Person对象
String json = "{"id":"1","name":"zhang","address":"Hubei"}";
Person person = gson.fromJson(json, Person.class);
System.out.println(person.getId()+" "+person.getAddress()+" "+person.getName());
//将集合转换为json字符串
Person person1 = new Person(1, "zhang", "Hubei");
Person person2 = new Person(2,"lu","DaWu");
List<Person> persons = new ArrayList<Person>();
persons.add(person1);
persons.add(person2);
String json = gson.toJson(persons);
//[{"id":1,"name":"zhang","address":"Hubei"},{"id":2,"name":"lu","address":"DaWu"}]
System.out.println(json);
//将json字符串组转换为多个对象
String json = "[{'id':'1','name':'zhang','address':'Hubei'},{'id':'2','name':'lu','address':'DaWu'}]";
List<Person> persons = gson.fromJson(json, new TypeToken<List<Person>>(){}.getType());
for(Person person : persons){
System.out.println(person.getId()+" "+person.getAddress()+" "+person.getName());
}
//注释:list string to string
List<String> list = new ArrayList<String>();
list.add("zhanglu");
list.add("hubei");
list.add("Dawu");
String json = gson.toJson(list);
//["zhanglu","hubei","Dawu"]
System.out.println(json);
//注释:json string to list<string>
String json = "['zhanglu','hubei','Dawu']";
List<String> list = gson.fromJson(json, new TypeToken<List<String>>(){}.getType());
for(String str : list){
System.out.println(str);
}
//Map<String,object> to json
Map<String, Person> map = new HashMap<String, Person>();
Person person = new Person(1, "zhanglu", "湖北大悟");
Person person2 = new Person(2, "Alone", "HuBeiDaWu");
map.put("person", person);
map.put("person2", person2);
String json = gson.toJson(map);
//{"person":{"id":1,"name":"zhanglu","address":"湖北大悟"},"person2":{"id":2,"name":"Alone","address":"HuBeiDaWu"}}
System.out.println(json);
//json to Map<Stirng,Object>
String json = "{"person":{"id":1,"name":"zhanglu","address":"湖北大悟"},"person2":{"id":2,"name":"Alone","address":"HuBeiDaWu"}}";
Map<String, Person> map = gson.fromJson(json, new TypeToken<Map<String,Person>>(){}.getType());
for(String key : map.keySet()){
System.out.println("key:"+key);
System.out.println((Person)map.get(key));
}
}
}