- 找到架包:
- 写测试代码:package com.pdsu.testgson;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONObject;
import org.json.JSONArray;
/*import org.json.JSONObject;
*/
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pdsu.bean.Person;
import com.pdsu.bean.Studet;
import com.pdsu.bean.zhongjian;
public class testGson {
private static String addgson(){
Gson gson = new Gson();
JSONObject json = null;
List<Person> persons = new ArrayList<Person>();
List<Studet> students=new ArrayList<Studet>();
for (int i = 0; i < 10; i++) {
Studet stu=new Studet();
stu.setStudentname("studentname"+i);
stu.setStudentage("Studentage"+i);
stu.setStudentid("studentid"+i);
students.add(stu);
}
/*for (int i = 0; i < 10; i++) {
Person p = new Person();
p.setName("name" + i);
p.setAge(i * 5);
persons.add(p);
}*/
zhongjian zhong=new zhongjian();
zhong.setCode(2000);
zhong.setMsg((ArrayList<Studet>) students);
String str = gson.toJson(zhong);
System.out.println(str);
return str;
}
public static <T> void main(String[] args) {
Gson gson = new Gson();
String str=addgson();
zhongjian zhong=null;
zhong=gson.fromJson(str,new TypeToken<zhongjian>(){}.getType());
List<T> per=zhong.getMsg();
String st=gson.toJson(per);
System.out.println(st);
List<Studet> ps = gson.fromJson(st, new TypeToken<List<Studet>>(){}.getType());
for(int i = 0; i < ps.size() ; i++)
{
Studet p = ps.get(i);
System.out.println(p.getStudentage());
}
}
}
-
对应两个持久化类:
package com.pdsu.bean;
import java.io.Serializable;
public class Person implements Serializable{
/**
* 人的持久化类
*/
private static final long serialVersionUID = -346553300839306202L;
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.pdsu.bean;
import java.io.Serializable;
public class Studet implements Serializable{
/**
* 学生持久化类
*/
private static final long serialVersionUID = -408317368251581075L;
private String studentid;
private String studentname;
private String studentage;
public String getStudentid() {
return studentid;
}
public void setStudentid(String studentid) {
this.studentid = studentid;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public String getStudentage() {
return studentage;
}
public void setStudentage(String studentage) {
this.studentage = studentage;
}
}
Gson的使用
最新推荐文章于 2024-04-14 16:28:17 发布