1 http://blog.csdn.net/lk_blog/article/details/7685169
2 List<Student> list = new ArrayList<Student>();
3 list.add(student1);
4 list.add(student2);
5 list.add(student3);
6
7 System.out.println("----------带泛型的List之间的转化-------------");
8 // 带泛型的list转化为json
9 String s2 = gson.toJson(list);
10 System.out.println("带泛型的list转化为json==" + s2);
11
12 // json转为带泛型的list
13 List<Student> retList = gson.fromJson(s2,
14 new TypeToken<List<Student>>() {
15 }.getType());
16 for (Student stu : retList) {
17 System.out.println(stu);
18 }
19
20 // 结果:
21 // 带泛型的list转化为json==[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 8:28:52 AM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 8:28:52 AM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 8:28:52 AM"}]
22 // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=1, name=李坤]
23 // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=2, name=曹贵生]
24 // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=3, name=柳波]
3、String->JsonObject
package package_1;
import java.lang.StringBuffer;
import java.awt.Window.Type;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.URL;
import net.sf.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonElement;
public class ChinaWeatherAPI {
public static void main(String[] args){
String jsonString = "{"field1":"value1","field2":"value2"}";
JsonParser parser = new JsonParser();
JsonObject jo = (JsonObject)parser.parse(jsonString);
JsonElement ele = jo.get("field1");
String value1 = ele.getAsString();
}
}