fastjson中List和JSONArray的相互转换

1.fastjson中List和JSONArray的相互转换

(1)List转换为JSONArray

List<T> list = new ArrayList<T>();
JSONArray array= JSONArray.parseArray(JSON.toJSONString(list))

(2)JSONArray转换为List

JSONArray array = new JSONArray();
List<EventColAttr> list = JSONObject.parseArray(array.toJSONString(), EventColAttr.class);

以上内容参考:CSDN博客


2.实例

创建一个User.java

public class User {

    private String name;
    private int age;

    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 [name=" + name + ", age=" + age + "]";
    }
}

(1)List转换为JSONArray

// list--->Json字符串-->JSONArray
    @Test
    public void test2(){
        //准备工作
        List<User> list = new ArrayList<User>();
        User user1 = new User();
        user1.setName("zhangsan");
        user1.setAge(14);
        User user2 = new User();
        user2.setName("lisi");
        user2.setAge(24);
        list.add(user1);
        list.add(user2);

        //转换为Json字符串
        String string = JSON.toJSONString(list);
        System.out.println("String为:"+string+",其类型为:"+string.getClass());
        //转换为JSONArray
        JSONArray array = JSON.parseArray(JSON.toJSONString(list));
        System.out.println("JSONArray为:"+array+",其类型为:"+array.getClass());

    }

运行结果:

String为:[{"age":14,"name":"zhangsan"},{"age":24,"name":"lisi"}],其类型为:class java.lang.String
JSONArray为:[{"name":"zhangsan","age":14},{"name":"lisi","age":24}],其类型为:class com.alibaba.fastjson.JSONArray

(2)JSONArray转换为List

// JSONArray--->Json字符串 ----->list
    @Test
    public void test3(){
        //准备工作
        List<User> list = new ArrayList<User>();
        User user1 = new User();
        user1.setName("zhangsan");
        user1.setAge(14);
        User user2 = new User();
        user2.setName("lisi");
        user2.setAge(24);
        list.add(user1);
        list.add(user2);
        JSONArray array = JSON.parseArray(JSON.toJSONString(list));

        //转换为Json字符串
        String string = array.toJSONString(array);
        System.out.println("String为:"+string+",其类型为:"+string.getClass());
        //转换为list
        List<User> list2 = JSON.parseArray(string, User.class);
        System.out.println("list为:"+list2+",其类型为:"+list2.getClass());
    }

运行结果:

String为:[{"name":"zhangsan","age":14},{"name":"lisi","age":24}],其类型为:class java.lang.String
list为:[User [name=zhangsan, age=14], User [name=lisi, age=24]],其类型为:class java.util.ArrayList

3.小结

以上内容如果存在错误,请指正。

你可能感兴趣的:(常用工具)