简述
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);
}