• json fastjson


    fastjson是阿里巴巴的开源JSON解析库,它可以解析JSON格式的字符串,支持将Java Bean序列化为JSON字符串,也可以从JSON字符串反序列化到JavaBean。

    在pom.xml文件引入以下声明,就可以使用

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.55</version>
            </dependency>

    使用举例:

    1,解析成字符串

    HashMap map = new HashMap();
            ArrayList<String> list = new ArrayList<String>();
            list.add("a");
            list.add("b");
            list.add("c");
            map.put("count", 12);
            map.put("list", list);
            System.out.println(JSON.toJSONString(map));
    // {"count":12,"list":["a","b","c"]}

    2,对象解析成json字符串

    public class User {
        private int id;
        private String phone;
        private String password;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getPhone() {
            return phone;
        }
    
        public void setPhone(String phone) {
            this.phone = phone;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
    }
    User user = new User();
            user.setId(1);
            user.setPassword("11");
            user.setPhone("11");
            System.out.println(JSON.toJSONString(user));
    //        {"id":1,"password":"11","phone":"11"}

    3,json字符串解析成对象

    String json = "{'id':'1','password':'11','phone':'11'}";
            JSONObject userJson = JSONObject.parseObject(json);
            User user = JSON.toJavaObject(userJson, User.class);
            System.out.println(user);
            System.out.println(user.getId());
    //        com.test.domain.User@443b7951
    //        1

    4,json字符数组转换

    String json = "[{'fileName':'aName','path':'ddd'},{'fileName':'bName','path':'ghgh'}]";
            List<Map<String, String>> listObjectFir = (List<Map<String, String>>) JSONArray.parse(json);
            for (Map<String, String> mapList : listObjectFir) {
                String fileName = mapList.get("fileName");
                String path = mapList.get("path");
                System.out.println("fileName:" + fileName + ",path:" + path);
            }
    //        fileName:aName,path:ddd
    //        fileName:bName,path:ghgh
  • 相关阅读:
    【PAT Advanced Level】1008. Elevator (20)
    模块的耦合和内聚
    《深入理解计算机系统》--链接
    HDU 1077Catching Fish(简单计算几何)
    [置顶] VC++界面编程之--自定义CEdit(编辑框)皮肤
    使用VS2012 开发SharePoint 2013 声明式的action(activity) 综合实例
    java 创建线程的三种方法Callable,Runnable,Thread比较及用法
    代码审计技巧讲解
    IP地址后面斜杠加具体数字详解
    80端口被system进程占用解决方法
  • 原文地址:https://www.cnblogs.com/luoa/p/10544943.html
Copyright © 2020-2023  润新知