使用fastjson进行自定义类的列表和字符串转换
1.环境
jdk1.8,fastjson
2.pom.xml
4.0.0
co.neutron.json
fastjson
0.0.1-SNAPSHOT
jar
fastjson
http://maven.apache.org
UTF-8
junit
junit
4.8
test
com.alibaba
fastjson
1.2.12
org.slf4j
slf4j-log4j12
1.7.2
package co.neutron.json.fastjson.entity;
public class User {
private int id;
private String name;
private int age;
public User() {
super();
}
public User(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
package co.neutron.json.fastjson;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import co.neutron.json.fastjson.entity.User;
public class ArrayListTest {
/*
* 测试内容如下
* 1.将User类型数组转换成json字符串
* 2.将json字符串转换成为User数组
*/
@Test
public void testArray2StringAndString2List() {
User user1 = new User(1, "张1", 11);
User user2 = new User(2, "张2", 12);
User user3 = new User(3, "张3", 13);
User user4 = new User(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"}]
*/
String userStr = 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 userList = JSON.parseArray(userStr, User.class);
userList.stream().forEach(System.err::println);
}
/**
* 测试包装类型的List转换为json字符串
*/
@Test
public void testList2String() {
List longs = new ArrayList();
longs.add(1L);
longs.add(2L);
longs.add(3L);
String actual = JSON.toJSONString(longs);
Assert.assertEquals("[1,2,3]", actual);
}
}