json-lib包可以将java对象转换为json。
下载json-lib包,或者struts2中已经集成了json-lib包。
为了以下演示例子。先定义一个学生类
public class Student {
private int age; //年龄
private String name; //姓名
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
例一:java对象--->json
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
Student student1=new Student();
student1.setAge(10);
student1.setName("王小虎");
JSONObject jsonObject = JSONObject.fromObject(student1);
System.out.println(jsonObject.toString());
}
}
打印输出内容:
{"age":10,"name":"王小虎"}
例二:java.util.List--->JavaScript Array
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
public class Test {
public static void main(String[] args) {
Student student1=new Student();
student1.setAge(10);
student1.setName("王小虎");
Student student2=new Student();
student2.setAge(11);
student2.setName("马小帅");
List list=new ArrayList();
list.add(student1);
list.add(student2);
JSONArray jsonObject = JSONArray.fromObject(list);
System.out.println(jsonObject.toString());
}
}
打印输出内容:
[{"age":10,"name":"王小虎"},{"age":11,"name":"马小帅"}]