FastJson之JSON和数组集合转换*

简述

JSON.parseArray json字符串转数组
JSON.toJSONString 数组转json字符串

案例

集合和JSON互相转换

/** * json转数组 */
@Test
public void arrayObjectAndJson() { 

   String jsonStringArray = "[{\"age\":3,\"birthdate\":1496738822842,\"name\":\"校长\",\"old\":true,\"salary\":123456789.0123},{\"age\":5," +
         "\"birthdate\":1496738822842,\"name\":\"学生\",\"old\":true,\"salary\":123456789.0123}]";
   /*json转数组*/
   List<User> userList = JSON.parseArray(jsonStringArray, User.class);
   System.out.println(userList.size());    // 输出 2
   System.out.println(userList);//[User{name='校长', age=3, salary=123456789.0123}, User{name='学生', age=5, salary=123456789.0123}]
   //数组转json
   String s = JSON.toJSONString(userList);
   System.out.println("s = " + s); //[{"age":3,"name":"校长","salary":123456789.0123},{"age":5,"name":"学生","salary":123456789.0123}]
}

基本数据类型数组转换

/** * 基本数据类型数组 */
@Test
public void arrayBaseTypeAndJson() { 
   int[] arr = { 1, 2, 3, 4, 5, 6, 7};
   String jsonString = JSON.toJSONString(arr);
   System.out.println("jsonString = " + jsonString);//jsonString = [1,2,3,4,5,6,7]

   //转成了集合了
   List<Integer> integers = JSON.parseArray(jsonString, Integer.class);
   System.out.println("integers = " + integers);
}

    原文作者:张俊杰1994
    原文地址: https://blog.csdn.net/qq_41489540/article/details/109071272
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞