zoukankan      html  css  js  c++  java
  • FastJson:json字符串与Java对象转换

     FastJson:json字符串与Java对象转换

    对象实体类(省略get set toString)

    class User {
        String name;
        String age;
        String sex;
    
        public User(){}
    
        public User(String name, String age, String sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
    }

    1.1、对象转json字符串

            User user1 = new User("丽丽","24","女");
            String jsonUser = JSONObject.toJSONString(user1);
            System.out.println(jsonUser);//{"age":"24","name":"丽丽","sex":"女"}

     1.2、 json字符串转对象

            JSONObject jsonStr = JSONObject.parseObject(jsonUser);
            User user2 = JSONObject.toJavaObject(jsonStr,User.class);


    //其他
    DataStore<ResidentDTO> residentDTODataStore = JSONObject.parseObject(String.valueOf(jsonStr), new TypeReference<DataStore<ResidentDTO>>() {});

    2.1、List转json字符串

            List<User> users = new ArrayList<>();
            User userTest1 = new User("李四", "22","男");
            User userTest2 = new User("王五", null,"男");
            users.add(userTest1);
            users.add(userTest2);
    
            String jsonUsers = JSONObject.toJSONString(users);//[{"age":"22","name":"李四","sex":"男"},{"name":"王五","sex":"男"}]

    2.2、json字符串转List

            List<User> userlist = JSON.parseArray(jsonUsers,User.class);//[User{name='李四', age='22', sex='男'}, User{name='王五', age='null', sex='男'}]

    3.1、Map 转json字符串

            Map<String, Object> map = new HashMap();
            map.put("user",user1);
            String mapJson = JSONObject.toJSONString(map);//{"user":{"age":"24","name":"丽丽","sex":"女"}}

    3.2、json字符串转Map

            JSONObject jsonMap = JSONObject.parseObject(mapJson);
            Map<String, Object> map1 = JSONObject.toJavaObject(jsonMap,Map.class);//{"user":{"sex":"女","name":"丽丽","age":"24"}}

    4、FastJson maven依赖

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.75</version>
    </dependency>
  • 相关阅读:
    STM32 串口DMA方式接收(转)
    STM32 串口功能 库函数 详解和DMA 串口高级运用(转载)
    内存泄露调试心得
    Android 5.0 5.1 webview 闪退问题
    ios 接入微信开发 新版
    ios 获取app版本号
    ios alamofire4.x网络框架url 中文问题
    微服务监控druid sql
    kotlin 单例模式
    mysql 数据库保存 微信分享时不能换行
  • 原文地址:https://www.cnblogs.com/omgliyq/p/14839494.html
Copyright © 2011-2022 走看看