前端之家收集整理的这篇文章主要介绍了
【第17篇】通过fastjson去操作对象数据并处理json数据,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package ivyy.taobao.com.entity;
import java.io.Serializable;
/**
*@Author:liangjl
*@Date:2014-12-19
*@Version:1.0
*@Description:
*/
public class Student implements Serializable{
private Integer age;
private String sex;
private String userName;
private String birthday;
private String address;
private String email;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package ivyy.taobao.com.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
*@Author:liangjl
*@Date:2014-12-19
*@Version:1.0
*@Description:
*/
public class Classz implements Serializable{
private List<Student> students=new ArrayList<Student>();
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
package ivyy.taobao.com.domain.fastjson;
import ivyy.taobao.com.entity.Classz;
import ivyy.taobao.com.entity.Student;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* @Author:jilongliang
* @Date:2014-12-19
* @Version:1.0
* @Description:通过fastjson去操作对象数据并处理json数据
*/
public class JsonTest2 {
public static void main(String[] args) {
//1、创建一个Student对象
Student stu1=new Student();
stu1.setAge(22);
stu1.setUserName("xiaoliang");
stu1.setSex("男");
//2、添加对象到List<Student>泛型
Classz claz1=new Classz();
claz1.getStudents().add(stu1);
//3、转成成JSON字符串
String jsonStr=JSON.toJSONString(claz1);
//4、创建一个JSONObject对象
JSONObject jsonObj=new JSONObject();
//5、转成成json对象
Object obj=jsonObj.parse(jsonStr);
System.out.println(obj);
//6、转成成Classz对象
Classz clz=JSON.parSEObject(jsonStr,Classz.class);
//7、拿出第0个Student对象
Student st=clz.getStudents().get(0);
System.out.println(st.getSex());
}
}