JSON.parseObject, is to convert the Json string into the corresponding object;
JSON.toJSONString: Convert array to Json string and List to json string
JSON.parseArray: Convert Json string to List
- /*
- * The test content is as follows
- * 1. Convert the User type array into a json string
- * 2. Convert json string to User array
- */
- @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};
- /*
- * Convert array to Json string
- * 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);
- }
- /**
- * Test the conversion of List of wrapper types to json strings
- */
- @Test
- publicvoid testList2String() {
- List<Long> longs = new ArrayList<Long>();
- longs.add(1L);
- longs.add(2L);
- longs.add(3L);
- String actual = JSON.toJSONString(longs);
- Assert.assertEquals("[1,2,3]", actual);
- }
- /*
- * Convert Json string to 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<User> userList = JSON.parseArray(userStr, User.class);
- userList.stream().forEach(System.err::println);