Convert list and json

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


  1.  /* 
  2.      * The test content is as follows 
  3.      * 1. Convert the User type array into a json string 
  4.      * 2. Convert json string to User array 
  5.      */  
  6.     @Test  
  7.     public void  testArray2StringAndString2List () {   
  8.         User user1 = new User(1"张1"11);  
  9.         User user2 = new User(2"张2"12);  
  10.         User user3 = new User(3"张3"13);  
  11.         User user4 = new User(4"张4"14);  
  12.         User[] users = {user1, user2, user3, user4};  
  13.           
  14.         /*  
  15.          * Convert array to Json string 
  16.          * result: 
  17.          * [{"age":11,"id":1,"name":"张1"},{"age":12,"id":2,"name":"张2"}, 
  18.          * {"age":13,"id":3,"name":"张3"},{"age":14,"id":4,"name":"张4"}] 
  19.          */  
  20.         String userStr = JSON.toJSONString(users);  
  21.     }


  1. /** 
  2.      * Test the conversion of List of wrapper types to json strings 
  3.      */  
  4.     @Test  
  5.     publicvoid testList2String() {   
  6.         List<Long> longs = new ArrayList<Long>();  
  7.         longs.add(1L);  
  8.         longs.add(2L);  
  9.         longs.add(3L);  
  10.         String actual = JSON.toJSONString(longs);  
  11.         Assert.assertEquals("[1,2,3]", actual);  
  12.     }  


  1. /* 
  2.          * Convert Json string to List 
  3.          * result 
  4.          * User [id=1, name=张1, age=11] 
  5.            User [id=2, name=张2, age=12] 
  6.            User [id=3, name=张3, age=13] 
  7.            User [id=4, name=张4, age=14] 
  8.          */  
  9.         List<User> userList = JSON.parseArray(userStr, User.class);  
  10.         userList.stream().forEach(System.err::println);  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326031518&siteId=291194637