如果要将数组、对象、Map、List转换成JSON数据,那我们需要一些jar包:
json-lib-2.4-jdk15.jar
ezmorph-1.0.6.jar
commons-logging.jar
commons-lang.jar
commons-collections.jar
commons-beanutils.jar
下面是与大家分享的代码:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
//将对象转成json
Student student = new Student();
student.setAge(18);
student.setName("zhangsan");
student.setSex("male");
JSONObject jsonObject = JSONObject.fromObject(student);
System.out.println(jsonObject);
//控制台输出{"age":18,"name":"zhangsan","sex":"male"}
//将数组或list转成json
Student[] stus = new Student[5];
List<Student> stuList = new ArrayList<Student>();
for (int i = 0; i < stus.length; i++) {
stus[i] = new Student();
stus[i].setAge(i*10+8);
stus[i].setName("zhang"+i);
stus[i].setSex("male");
//添加到list,一会儿用
stuList.add(stus[i]);
}
JSONArray jsonArray = JSONArray.fromObject(stus);
System.out.println