List集合转String、String转List集合
首先导入alibaba的jar包
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.54</version> </dependency>
构建集合对象
People people1 = new People("小范", 1, 23); People people2 = new People("小张", 1, 26); People people3 = new People("小顾", 2, 25); List<People> list = new ArrayList<>(); list.add(people1); list.add(people2); list.add(people3); System.out.println("原装List:" + list); System.out.println("================================");
List集合转String
/** *List转string */ String listToString = JSON.toJSONString(list); System.out.println("List转String结果:" + listToString); System.out.println("=================================");
String转List集合
/** *String转List */ List<People> stringToList = JSON.parseArray(listToString, People.class); System.out.println("String转List结果:" + stringToList);
输出结果:
原装List:[People{ name=小范, sex=1, year=23}, People{ name=小张, sex=1, year=26}, People{ name=小顾, sex=2, year=25}] =========================================== List转String结果:[{ "name":"小范","sex":1,"year":23},{ "name":"小张","sex":1,"year":26},{ "name":"小顾","sex":2,"year":25}] =========================================== String转List结果:[People{ name=小范, sex=1, year=23}, People{ name=小张, sex=1, year=26}, People{ name=小顾, sex=2, year=25}]
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
《程序员修炼之道》第2版