本文共 2096 字,大约阅读时间需要 6 分钟。
在pom.xml中添加必要的依赖:
junit junit 4.8 test com.alibaba fastjson 1.2.12 org.slf4j slf4j-log4j12 1.7.2
定义用于测试的数据实体类User:
package co.neutron.json.fastjson.entity;public class User { private int id; private String name; private int age; public User(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; }} 测试ArrayListTest类,验证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 { @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字符串 String userStr = JSON.toJSONString(users); // 将Json字符串转换为List List userList = JSON.parseArray(userStr, User.class); // 输出测试结果 userList.forEach(System.err::println); Assert.assertNotNull(userList); Assert.assertEquals(4, userList.size()); } @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); }} 通过以上配置和实现,可以轻松地使用fastjson进行自定义类的列表与字符串转换。其中,fastjson的JSON.toJSONString和JSON.parseArray方法分别用于将对象序列化为Json字符串和反序列化为对象列表,实现了便捷的数据转换功能。
转载地址:http://jngfk.baihongyu.com/