在javaweb中,有时候需要返回json数据到前端页面,这里列举一个把list数据格式转换成json数据格式的util类,可以把此类放在项目的util工具包下使用。
package com.pifeng.util;
import java.lang.reflect.Field;
import java.util.List;
/**
* @author pifeng 把list转换成json格式
* @param <T>
* @Date 2015-4-10
*/
public class ListToJson<T> {
public String listToJson(List<T> list) {
// 变量
StringBuffer jsonStr = new StringBuffer();
// 前提条件
if (null == list || 0 == list.size()) {
return null;
}
// class对象
Class<?> classType = list.get(0).getClass();
// 得到javabean的名字
String javaBeanClassName = classType.getSimpleName();
jsonStr.append("{\"").append(javaBeanClassName.toLowerCase()).append("s").append("\":[");
// 此JavaBean中所声明的所有字段
Field[] fields = classType.getDeclaredFields();
for (int i = 0; i < list.size(); i++) {
jsonStr.append("{");
for (Field field : fields) {
// 得到字段名
String fieldName = field.getName();
field.setAccessible(true);
// 得到指定对象上此 Field 表示的字段的值
Object fieldValue;
try {
fieldValue = field.get(list.get(i));
jsonStr.append("\"").append(fieldName.toLowerCase()).append("\":").append("\"").append(fieldValue).append("\"").append(",");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
jsonStr.deleteCharAt(jsonStr.length() - 1);
jsonStr.append("},");
}
jsonStr.deleteCharAt(jsonStr.length() - 1);
jsonStr.append("]}");
return jsonStr.toString();
}
}
测试类:
package test;
import java.util.*;
import com.pifeng.entity.Student;
import com.pifeng.util.ListToJson;
public class TestListToJson {
/**
* @param args
*/
public static void main(String[] args) {
// 创建一个list 测试学生
List<Student> list = new ArrayList<Student>();
list.add(new Student(1, "张三", 20, true, new Date()));
list.add(new Student(2, "李四", 20, true, new Date()));
list.add(new Student(3, "王五", 20, false, new Date()));
list.add(new Student(4, "赵六", 20, true, new Date()));
list.add(new Student(5, null, 20, true, new Date()));
String json = new ListToJson<Student>().listToJson(list);
System.out.println(json);
}
}
测试结果:{"students":[{"age":"20","birthday":"Mon Dec 28 22:23:50 CST 2015","id":"1","name":"张三","sex":"true"},{"age":"20","birthday":"Mon Dec 28 22:23:50 CST 2015","id":"2","name":"李四","sex":"true"},{"age":"20","birthday":"Mon Dec 28 22:23:50 CST 2015","id":"3","name":"王五","sex":"false"},{"age":"20","birthday":"Mon Dec 28 22:23:50 CST 2015","id":"4","name":"赵六","sex":"true"},{"age":"20","birthday":"Mon Dec 28 22:23:50 CST 2015","id":"5","name":"null","sex":"true"}]}