使用fastjson进行自定义类的列表和字符串转换
1.环境
jdk1.8,fastjson
2.pom.xml
[html]view plaincopy<projectxmlns="/POM/4.0.0"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>co.neutron.json</groupId><artifactId>fastjson</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>fastjson</name><url></url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.8</version><scope>test</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.12</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.2</version></dependency></dependencies></project>
3.实体类[html]view plaincopypackageco.neutron.json.fastjson.entity;publicclassUser{privateintid;privateStringname;privateintage;publicUser(){super();}publicUser(intid,Stringname,intage){super();this.id=id;this.name=name;this.age=age;}publicintgetId(){returnid;}publicvoidsetId(intid){this.id=id;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicintgetAge(){returnage;}publicvoidsetAge(intage){this.age=age;}@OverridepublicStringtoString(){return"User[id="+id+",name="+name+",age="+age+"]";}}
4.测试类[java]view plaincopypackageco.neutron.json.fastjson;importjava.util.ArrayList;importjava.util.List;importorg.junit.Assert;importorg.junit.Test;importcom.alibaba.fastjson.JSON;importco.neutron.json.fastjson.entity.User;publicclassArrayListTest{/**测试内容如下*1.将User类型数组转换成json字符串*2.将json字符串转换成为User数组*/@TestpublicvoidtestArray2StringAndString2List(){Useruser1=newUser(1,"张1",11);Useruser2=newUser(2,"张2",12);Useruser3=newUser(3,"张3",13);Useruser4=newUser(4,"张4",14);User[]users={user1,user2,user3,user4};/**将数组转换为Json字符串*result:*[{"age":11,"id":1,"name":"张1"},{"age":12,"id":2,"name":"张2"},*{"age":13,"id":3,"name":"张3"},{"age":14,"id":4,"name":"张4"}]*/StringuserStr=JSON.toJSONString(users);/**将Json字符串转换为List*result*User[id=1,name=张1,age=11]User[id=2,name=张2,age=12]User[id=3,name=张3,age=13]User[id=4,name=张4,age=14]*/List<User>userList=JSON.parseArray(userStr,User.class);userList.stream().forEach(System.err::println);}/***测试包装类型的List转换为json字符串*/@TestpublicvoidtestList2String(){List<Long>longs=newArrayList<Long>();longs.add(1L);longs.add(2L);longs.add(3L);Stringactual=JSON.toJSONString(longs);Assert.assertEquals("[1,2,3]",actual);}}