java对象与JSON字符串互转
想完成java对象转换成JSON字符串必须在项目中导入以下jar包,缺一不可:
首先创建一个实体类Student.java
package com.zhk.bean;
public class Student {
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;
}
@Override
public String toString(){
return this.name+" "+this.age;
}
}
其次创建TestJson.java类
package com.zhk.jsontojava;
import java.util.ArrayList;
import java.util.List;
import com.zhk.bean.Student;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TestJson {
//java对象转为json字符串
public static void test1(){
Student stu = new Student();
stu.setName("James");
stu.setAge(35);
JSONObject jsonobj = JSONObject.fromObject(stu);
String jsonstr = jsonobj.toString();
System.out.println(jsonstr);
}
//java数组(集合)转换为JSON字符串
public static void test2(){
List<Student> slist = new ArrayList<Student>();
for(int i=0;i<3;i++){
Student stu = new Student();
stu.setName("zhang"+i);
stu.setAge(20+i+1);
slist.add(stu);
}
JSONArray jsonarray = JSONArray.fromObject(slist);
String jsonstr = jsonarray.toString();
System.out.println(jsonstr);
}
//json字符串转换为java对象
public static void test3(){
String jsonstr = "{\"name\":\"zhang\",\"age\":15}";
JSONObject jsonobj = JSONObject.fromObject(jsonstr);
Student stu = (Student) JSONObject.toBean(jsonobj, Student.class);
System.out.println(stu);
}
//JSON字符串转换成java数组(集合)
public static void test4(){
String jsonstr = "[{\"name\":\"zhang\",\"age\":15},"+
"{\"name\":\"zhao\",\"age\":16},"+
"{\"name\":\"wang\",\"age\":25}]";
JSONArray jsonsrr = JSONArray.fromObject(jsonstr);
List<Student> slist = (List<Student>) JSONArray.toCollection(jsonsrr, Student.class);
for (Student student : slist) {
System.out.println(student);
}
}
public static void main(String[] args) {
//test1();
//test2();
//test3();
test4();
}
}