import
implementation 'com.alibaba.fastjson2:fastjson2:2.0.42'
import com.alibaba.fastjson.JSON;
public class FastJsonExample {
    public static void main(String[] args) {
        // Serialize Java object to JSON
        User user = new User("John Doe", 25);
        String json = JSON.toJSONString(user);
        System.out.println("Serialized JSON: " + json);
        // Deserialize JSON to (User) Java object
        String jsonStr = "{\"name\":\"Alice Smith\",\"age\":25}";
        User newUser = JSON.parseObject(jsonStr, User.class);
        System.out.println("Deserialized User: " + newUser.getName() + ", " + newUser.getAge());
        List<User> userList = userMapper.selectList(null);
        // Serialize Java object to JSON
        String json = JSON.toJSONString( userList );
        // 将 JSON 数组字符串解析为 User 对象列表
        // String jsonArrayString = 
        // "[
        //   {\"id\":1,\"name\":\"Alice\",\"email\":\"alice@example.com\"}, 
        //   {\"id\":2,\"name\":\"Bob\",\"email\":\"bob@example.com\"}
        //  ]";
        List<User> UserList1 = JSON.parseArray(json, User.class);
   
        // 创建一个列表来存储User对象的 UserName
        List<Integer> UserNameList = new ArrayList<>();
        // 输出解析后的对象列表
        // 遍历 User 对象列表并提取 所需字段
        for (User user : userListList) {
            System.out.println(user.getUserName());
            // 列表存储每个User对象的 UserName
            UserNameList.add(user.getUserName());
        }
        // 将列表转换为数组
        Integer[] UserNameListArray = UserNameList.toArray(new Integer[0]);
        log.info(Arrays.toString(UserNameListArray));
        
    }
    static class User {
        private String name;
        private int age;
        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public int getAge() {
            return age;
        }
    }
}
在上面的示例中,我们使用 FastJSON 库将一个 Java 对象序列化为 JSON 格式的数据,并将 JSON 数据反序列化为 Java 对象。通过调用 JSON.toJSONString() 方法可以将 Java 对象转换为 JSON 字符串,调用 JSON.parseObject() 方法可以将 JSON 字符串转换为 Java 对象。这样可以方便地在 Java 应用程序中进行对象和 JSON 数据之间的转换。
 
                   
                   
                   
                   
                             
       
           
                 
                 
                 
                 
                 
                
               
                 
                 
                 
                 
                
               
                 
                 扫一扫
扫一扫
                     
              
             
                   5323
					5323
					
 被折叠的  条评论
		 为什么被折叠?
被折叠的  条评论
		 为什么被折叠?
		 
		  到【灌水乐园】发言
到【灌水乐园】发言                                
		 
		 
    
   
    
   
             
            


 
            