fastjson常见使用

maven依赖包:



    com.alibaba
    fastjson
    1.2.47

测试所需的实体类

    package com.xxx.controller;
     
    import java.io.Serializable;
    public class Data implements Serializable {
        private static final long serialVersionUID = -6957361951748382519L;
        private String id;
        private String suborderNo;
        private String organUnitType;
        private String action;
        private String parent;
        private String organUnitFullName;
        private Long ordinal;
        get、set方法省略。。。
    }

    package com.xxx.controller;
     
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;
     
    public class Error implements Serializable {
     
        private static final long serialVersionUID = -432908543160176349L;
     
        private String code;
        private String message;
        private String success;
        private List data = new ArrayList<>();
      get、set方法省略。。。
    }

四、JSON格式字符串、JSON对象及JavaBean之间的相互转换

4.1) JAVA对象转JSON字符串

    //java对象转json字符串
        public static void beanTojson() {
            Data data = new Data();
            data.setAction("add");
            data.setId("1");
            data.setOrdinal(8L);
            data.setOrganUnitFullName("testJSON");
            data.setParent("0");
            data.setSuborderNo("58961");
     
            String s = JSON.toJSONString(data);
            System.out.println("toJsonString()方法:s=" + s);
            //输出结果{"action":"add","id":"1","ordinal":8,"organUnitFullName":"testJSON","parent":"0","suborderNo":"58961"}
        }
4.2)  A. JSON字符串转JSON对象

    //json字符串转json对象
        public static void jsonToJsonBean() {
            String s ="{\"action\":\"add\",\"id\":\"1\",\"ordinal\":8,\"organUnitFullName\":\"testJSON\",\"parent\":\"0\",\"suborderNo\":\"58961\"}";
     
            JSONObject jsonObject = JSON.parseObject(s);
            String action = jsonObject.getString("action");
            String id = jsonObject.getString("id");
            System.out.println("action ="+action);//add
            System.out.println("id ="+id);//1
            System.out.println("jsonObject ="+jsonObject);
            //action =add
            //id =1
            //jsonObject ={"parent":"0","organUnitFullName":"testJSON","action":"add","id":"1","suborderNo":"58961","ordinal":8}
        }
    B. 复杂JSON格式字符串与JSONObject之间的转换
     public static void jsonToBean() {
            String str ="{\"meta\":{\"code\":\"0\",\"message\":\"同步成功!\"},\"data\":{\"orderno\":\"U_2018062790915774\",\"suborderno\":\"SUB_2018062797348039\",\"type\":\"organunit\",\"result\":{\"organunit\":{\"totalCount\":2,\"successCount\":0,\"failCount\":2,\"errors\":[{\"code\":\"UUM70004\",\"message\":\"组织单元名称不能为空\",\"data\":{\"id\":\"254\",\"suborderNo\":\"SUB_2018062797348039\",\"organUnitType\":\"部门\",\"action\":\"add\",\"parent\":\"10000\",\"ordinal\":0,\"organUnitFullName\":\"组织单元全称\"},\"success\":false},{\"code\":\"UUM70004\",\"message\":\"组织单元名称不能为空\",\"data\":{\"id\":\"255\",\"suborderNo\":\"SUB_2018062797348039\",\"organUnitType\":\"部门\",\"action\":\"add\",\"parent\":\"10000\",\"ordinal\":0,\"organUnitFullName\":\"组织单元全称\"},\"success\":false}]},\"role\":{\"totalCount\":0,\"successCount\":0,\"failCount\":0,\"errors\":[]},\"user\":{\"totalCount\":0,\"successCount\":0,\"failCount\":0,\"errors\":[]}}}}";
            JSONObject jsonObject = JSON.parseObject(str);
            JSONObject data = jsonObject.getJSONObject("data");
            JSONObject result = data.getJSONObject("result");
     
            String organunit1 = result.getString("organunit");
            System.out.println(organunit1);
            JSONObject organunit = result.getJSONObject("organunit");
     
            JSONArray errors2 = organunit.getJSONArray("errors");
     
            List error = JSON.parseObject(errors2.toJSONString(), new TypeReference>() {
            });
        }

4.3) A. JSON字符串转JAVA简单对象

    //json字符串转java简单对象
        public static void jsonStrToJavaBean() {
            String s ="{\"action\":\"add\",\"id\":\"1\",\"ordinal\":8,\"organUnitFullName\":\"testJSON\",\"parent\":\"0\",\"suborderNo\":\"58961\"}";
            Data data = JSON.parseObject(s, Data.class);
            System.out.println("data对象"+data.toString());
            System.out.println("action="+data.getAction()+"---id="+data.getId());
            //data对象Data{id='1', suborderNo='58961', organUnitType='null', action='add', parent='0', organUnitFullName='testJSON', ordinal=8}
            //action=add---id=1
     
            /**
             * 另一种方式转对象
             */
            Data dd = JSON.parseObject(s, new TypeReference() {});
            System.out.println("另一种方式获取data对象"+dd.toString());
            System.out.println("另一种方式获取="+dd.getAction()+"---id="+dd.getId());
            //另一种方式获取data对象Data{id='1', suborderNo='58961', organUnitType='null', action='add', parent='0', organUnitFullName='testJSON', ordinal=8}
            //另一种方式获取=add---id=1
        }

       B. JSON字符串  数组类型与JAVA对象的转换

测试json字符串

{"errors":[{"code":"UUM70004","message":"组织单元名称不能为空","data":{"id":"254","suborderNo":"SUB_2018062797348039","organUnitType":"部门","action":"add","parent":"10000","ordinal":0,"organUnitFullName":"组织单元全称"},"success":false},{"code":"UUM70004","message":"组织单元名称不能为空","data":{"id":"255","suborderNo":"SUB_2018062797348039","organUnitType":"部门","action":"add","parent":"10000","ordinal":0,"organUnitFullName":"组织单元全称"},"success":false}]}

    //json字符串--数组型与JSONArray对象之间的转换
        public static void jsonStrToJSONArray() {
            String str = "{\"errors\":[{\"code\":\"UUM70004\",\"message\":\"组织单元名称不能为空\",\"data\":{\"id\":\"254\",\"suborderNo\":\"SUB_2018062797348039\",\"organUnitType\":\"部门\",\"action\":\"add\",\"parent\":\"10000\",\"ordinal\":0,\"organUnitFullName\":\"组织单元全称\"},\"success\":false},{\"code\":\"UUM70004\",\"message\":\"组织单元名称不能为空\",\"data\":{\"id\":\"255\",\"suborderNo\":\"SUB_2018062797348039\",\"organUnitType\":\"部门\",\"action\":\"add\",\"parent\":\"10000\",\"ordinal\":0,\"organUnitFullName\":\"组织单元全称\"},\"success\":false}]}";
            JSONObject jsonObject = JSON.parseObject(str);
            JSONArray error = jsonObject.getJSONArray("errors");
            List errors = JSON.parseObject(error.toJSONString(), new TypeReference>() {
            });
            for (Error e: errors) {
                //Error的属性
                System.out.println("Error属性="+e.getSuccess());
                System.out.println("Error属性="+e.getCode());
                System.out.println("Error属性="+e.getMessage());
                //Error集合属性
                List datas = e.getData();
                for (Data d: datas) {
                    System.out.println("data对象属性="+d.getId());
                    System.out.println("data对象属性="+d.getAction());
                    System.out.println("data对象属性="+d.getSuborderNo());
                }
            }
            //Error属性=false
            //Error属性=UUM70004
            //Error属性=组织单元名称不能为空
            //data对象属性=254
            //data对象属性=add
            //data对象属性=SUB_2018062797348039
     
            //Error属性=false
            //Error属性=UUM70004
            //Error属性=组织单元名称不能为空
            //data对象属性=255
            //data对象属性=add
            //data对象属性=SUB_2018062797348039
        }
    C. JSON字符串  第二种方法-->数组类型与JAVA对象的转换

   //第二种方法:json字符串--数组型与JSONArray对象之间的转换
        @Test
        public void jsonStrToJSONArray2() {
            String str = "{\"errors\":[{\"code\":\"UUM70004\",\"message\":\"组织单元名称不能为空\",\"data\":{\"id\":\"254\",\"suborderNo\":\"SUB_2018062797348039\",\"organUnitType\":\"部门\",\"action\":\"add\",\"parent\":\"10000\",\"ordinal\":0,\"organUnitFullName\":\"组织单元全称\"},\"success\":false},{\"code\":\"UUM70004\",\"message\":\"组织单元名称不能为空\",\"data\":{\"id\":\"255\",\"suborderNo\":\"SUB_2018062797348039\",\"organUnitType\":\"部门\",\"action\":\"add\",\"parent\":\"10000\",\"ordinal\":0,\"organUnitFullName\":\"组织单元全称\"},\"success\":false}]}";
            //获取jsonobject对象
            JSONObject jsonObject = JSON.parseObject(str);
            //把对象转换成jsonArray数组
            JSONArray error = jsonObject.getJSONArray("errors");
            //error==>[{"code":"UUM70004","message":"组织单元名称不能为空","data":{"id":"254","suborderNo":"SUB_2018062797348039","organUnitType":"部门","action":"add","parent":"10000","ordinal":0,"organUnitFullName":"组织单元全称"},"success":false},{"code":"UUM70004","message":"组织单元名称不能为空","data":{"id":"255","suborderNo":"SUB_2018062797348039","organUnitType":"部门","action":"add","parent":"10000","ordinal":0,"organUnitFullName":"组织单元全称"},"success":false}]
            //将数组转换成字符串
            String jsonString = JSONObject.toJSONString(error);//将array数组转换成字符串
            //将字符串转成list集合
            List  errors = JSONObject.parseArray(jsonString, Error.class);//把字符串转换成集合
            for (Error e: errors) {
                //Error的属性
                System.out.println("另一种数组转换Error属性="+e.getSuccess());
                System.out.println("另一种数组转换Error属性="+e.getCode());
                System.out.println("另一种数组转换Error属性="+e.getMessage());
                //Error集合属性
                List datas = e.getData();
                for (Data d: datas) {
                    System.out.println("另一种数组转换data对象属性="+d.getId());
                    System.out.println("另一种数组转换data对象属性="+d.getAction());
                    System.out.println("另一种数组转换data对象属性="+d.getSuborderNo());
                }
            }
            //另一种数组转换Error属性=false
            //另一种数组转换Error属性=UUM70004
            //另一种数组转换Error属性=组织单元名称不能为空
            //另一种数组转换data对象属性=254
            //另一种数组转换data对象属性=add
            //另一种数组转换data对象属性=SUB_2018062797348039
     
            //另一种数组转换Error属性=false
            //另一种数组转换Error属性=UUM70004
            //另一种数组转换Error属性=组织单元名称不能为空
            //另一种数组转换data对象属性=255
            //另一种数组转换data对象属性=add
            //另一种数组转换data对象属性=SUB_2018062797348039
        }

4.4) JAVA对象转JSON对象

    //javabean转json对象
        public static void jsonBenToJsonObject() {
            Data data = new Data();
            data.setAction("add");
            data.setId("1");
            data.setOrdinal(8L);
            data.setOrganUnitFullName("testJSON");
            data.setParent("0");
            data.setSuborderNo("58961");
            JSONObject jsonObj = (JSONObject) JSON.toJSON(data);
            JSON json = (JSON) JSON.toJSON(data);
            System.out.println("jsonObj"+jsonObj);
            System.out.println("json对象"+json);
            //jsonObj{"parent":"0","organUnitFullName":"testJSON","action":"add","id":"1","suborderNo":"58961","ordinal":8}
            //json对象{"parent":"0","organUnitFullName":"testJSON","action":"add","id":"1","suborderNo":"58961","ordinal":8}
        }
    /**
         * 通过fastjson把字符串转换成泛型数组
         * TypeReference
         */
        public static void string2List(){
            StringBuffer buffer=new StringBuffer();
            buffer.append("[{");
                buffer.append("\"age\":").append("27").append(",");
                buffer.append("\"userName\":").append("\"龙叔\"").append(",");
                buffer.append("\"address\":").append("\"广东省云浮市\"");
            buffer.append("}]");
            
            String jsonText=buffer.toString();
            //转成成数组
            Student[] stu2 = JSON.parseObject(jsonText,new TypeReference(){});  
            List list = Arrays.asList(stu2);
            
            for(Student st:list){
                System.out.println(st.getAddress());
            }
            
            // 转换成ArrayList
            ArrayList list2 = JSON.parseObject(jsonText, new TypeReference>(){}); 
            
            for (int i = 0; i < list2.size(); i++) {
                Student obj =(Student) list2.get(i);
                System.out.println(obj.getAddress());
            }
            
        }
        /**
         * 通过fastjson把Map换成字符串转
         */
        public static void map2json(){
            //创建一个Map对象
             Map map = new HashMap();
             map.put("username", "周伯通");
             map.put("address", "广东省仙游谷");
             map.put("age", "198");
             String json = JSON.toJSONString(map,true); //转成JSON数据
             
             Map map1 = (Map)JSON.parse(json); 
             //遍历数组数据
             for (String key : map1.keySet()) { 
                System.out.println(key+":"+map1.get(key)); 
            } 
        }
        /**
         * 通过fastjson把Map换成字符串转
         */
        public static void map2JSON() {
            Map map = new HashMap();
            map.put("username", "周伯通");
            map.put("address", "广东省仙游谷");
            map.put("age", "198");
            String json = JSON.toJSONString(map);
            Map map1 = JSON.parseObject(json);
            for (Object obj : map.entrySet()) {
                Map.Entry entry = (Map.Entry) obj;
                System.out.println(entry.getKey() + "--->" + entry.getValue());
            }
        } 
    }



    package ivyy.taobao.com.entity;
     
    import java.io.Serializable;
     
    /**
     *@Author:liangjl
     *@Date:2014-12-19
     *@Version:1.0
     *@Description:
     */
    public class Student implements Serializable{
        private Integer age;
        private String sex;
        private String userName;
        private String birthday;
        private String address;
        private String email;
        
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        public String getUserName() {
            return userName;
        }
        public void setUserName(String userName) {
            this.userName = userName;
        }
        public String getBirthday() {
            return birthday;
        }
        public void setBirthday(String birthday) {
            this.birthday = birthday;
        }
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address = address;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
    }


你可能感兴趣的:(fastjson常见使用)