import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; public class JsonUtils { /*** * 将List对象序列化为JSON文本 */ public static String toJSONString(Object obj) { return JSON.toJSONString(obj); } /*** * 将字符串转换为传入类型的List */ public static <T> List<T> toList(String text, Class<T> clazz){ return JSONArray.parseArray(text, clazz); } /*** * 将字符串转换为传入类型的List */ public static <T> Object toObj(String text, Class<T> clazz){ return JSON.parseObject(text, clazz); } }
测试
Student s = Student.getStu(); // 将对象转成json字符串 System.out.println(JsonUtils.toJSONString(s)); // 将json字符串转成对象 Object s2 = JsonUtils.toObj(JsonUtils.toJSONString(s), Student.class); System.out.println(s2.toString()); // 将List 转成json字符串 List<Student> list = new ArrayList<>(); Student stu1 = Student.getStu(); Student stu2 = Student.getStu(); list.add(stu1); list.add(stu2); System.out.println(JsonUtils.toJSONString(list)); // 将json字符串转成List List<Student> list2 = JsonUtils.toList(JsonUtils.toJSONString(list), Student.class); for (Student student : list2) { System.out.println(JsonUtils.toJSONString(student)); }
原文地址:https://www.cnblogs.com/lyon91/p/9729518.html
时间: 2024-10-22 22:13:47