<small id="7ktuj"></small>
      <bdo id="7ktuj"></bdo>
        <mark id="7ktuj"></mark>

        <source id="7ktuj"></source>
        <small id="7ktuj"></small>

        ITPub博客

        首頁 > 應用開發 > Java > java基礎之泛型對象與json互轉

        java基礎之泛型對象與json互轉

        原創 Java 作者:蝴蝶飛啊飛 時間:2019-10-12 10:53:16 0 刪除 編輯

        、引入jar

        使用JSONObject 必須引用 JSON-lib.jar, 同時它還依賴于其他包

        common-lang.jar

        common-beanuitls.jar

        common-collections.jar

        common-logging.jar

        ezmorph.jar

        二、JSONObject 對象使用

        JSON-lib 包是一個 java 對象、 xml JSON 互相轉換的包。

        1. Java 對象轉換成 json 字符串

        Person p1=new Person();

        p1.setName("sunshine");

        p1.setAge(26);

        String jsonStr=JSONObject.fromObject(p1).toString();

        2. Java 集合轉換成 json 字符串

                Person p1=new Person();p1.setName("A1");p1.setAge(26);

                Person p2=new Person();p2.setName("A2");p2.setAge(23);

                List personList=new ArrayList<Person>();

                personList.add(p1);

                personList.add(p2);

                 Map personMap=new HashMap<String, Person>();

                personMap.put("p1", p1);

                personMap.put("p2", p2);

                //[{"age":26,"name":"A1"},{"age":23,"name":"A2"}]

                JSONArray.fromObject(personList).toString();

         JSONSerializer.toJSON(personList)

                //[{"p2":{"name":"A2","age":23},"p1":{"name":"A1","age":26}}]

                JSONArray.fromObject(personMap).toString();

         JSONSerializer.toJSON(personMap)

        3. json 字符串轉換成動態 Java 對象

         String jsonStr="[{\"name\":\"A2\",\"age\":23},{\"name\":\"A1\",\"age\":26}]";

                JSONArray ja=JSONArray.fromObject(jsonStr);

                for(int i=0;i<ja.size();i++){

                    JSONObject jo= ja.getJSONObject(i); // 轉換成 JSONObject 對象

                    System.out.println(jo.get("name"));

         

                    Person p=(Person)JSONObject.toBean(jo,Person.class);    // 轉換成 JavaBean

                    System.out.println(p.getName());

                }

        4. 解決 json 中字段和 java 類的關鍵字沖突的問題,如果你的外匯IBhttp://www.kaifx.cn/ json 中含有關鍵字和 java 的關鍵字沖突怎么解決。加上 @SerializedName("")  ,加入 json 中有一個字段為 abstract ,你的 java 類中肯定不能有這個一個屬性,解決方法。如下:

        @SerializedName(" abstract")

        public String abstracttext;

        把泛型對象轉成字符串放到緩存中

         public static void main(String[] args) {

                VO<UserParm> vo = new VO<UserParm>();

                UserParm user = new UserParm();

                user.setUserIdName("1111");

                user.setMobilePhoneNo("2222");

                vo.setData(user);

                // 正常情況

                //1. 對象轉 json str

                String str = JSONObject.toJSONString(vo);

                System.out.println(str);

                //2,json str 轉對象

                VO vojs= JSONObject.parseObject(str,VO.class);

                System.out.println(vojs);

                // 泛型 不能使用強轉,不管用,報錯

                VO<UserParm> vojs2= JSONObject.parseObject(str,VO.class);

                System.out.println(vojs2);

        //        System.out.println(vojs2.getData().getMobilePhoneNo());

                // 泛型,正常轉換

                VO<UserParm> vojs3= JSONObject.parseObject(str,new TypeReference<VO<UserParm>>(){});

                System.out.println(vojs3.getData().getMobilePhoneNo());

            }

        說明:

        1 ) 用的是阿里的 fastjson pom 文件中增加下依賴

               <dependency>

                    <groupId>com.alibaba</groupId>

                    <artifactId>fastjson</artifactId>

                    <version>1.2.46</version>

                </dependency>

        2 )對象轉 json 格式 str

         String str = JSONObject.toJSONString(vo);

        3 json 格式 str 轉對象

         VO vojs= JSONObject.parseObject(str,VO.class)

        4 )泛型的不一樣,轉換為泛型對象 UserParm 的時候會報錯。

        System.out.println(vojs2.getData().getMobilePhoneNo());

        com.alibaba.fastjson.JSONObject cannot be cast to com.laowang.spcrud.entity.UserPar

        泛型的需要使用TypeReference 才行:

           VO<UserParm> vojs3= JSONObject.parseObject(str,new TypeReference<VO<UserParm>>(){});

        5 )結果展示

        com.laowang.spcrud.service.TestService

        {"code":"0","data":{"mobilePhoneNo":"2222","userIdName":"1111"}}

        com.laowang.spcrud.entity.VO@368239c8

        com.laowang.spcrud.entity.VO@9e89d68

        2222

        Process finished with exit code 0

        兩個對象類

        1 )泛型類 VO

        package com.laowang.spcrud.entity;

        import java.io.Serializable;

        public class VO<T> implements Serializable {

            public static final String SUCCESS = "0";

            public static final String FAIL = "1";

            private static final long serialVersionUID = 1L;

            private String code = SUCCESS;

            private String msg;

            private T data;

            

            public static String getSUCCESS() {

                return SUCCESS;

            }

            public static String getFAIL() {

                return FAIL;

            }

            public static long getSerialVersionUID() {

                return serialVersionUID;

            }

            public String getCode() {

                return code;

            }

            public void setCode(String code) {

                this.code = code;

            }

            public String getMsg() {

                return msg;

            }

            public void setMsg(String msg) {

                this.msg = msg;

            }

            public T getData() {

                return data;

            }

            public void setData(T data) {

                this.data = data;

            }

        }

        2 )實體類 UserParm

        package com.laowang.spcrud.entity;

        import java.io.Serializable;

        public class UserParm implements Serializable {

            private static final long serialVersionUID = 1L;

            private String mobilePhoneNo;

            private String email;

            private String uid;

            private String userIdName;

            public static long getSerialVersionUID() {

                return serialVersionUID;

            }

            public String getMobilePhoneNo() {

                return mobilePhoneNo;

            }

            public void setMobilePhoneNo(String mobilePhoneNo) {

                this.mobilePhoneNo = mobilePhoneNo;

            }

            public String getEmail() {

                return email;

            }

            public void setEmail(String email) {

                this.email = email;

            }

            public String getUid() {

                return uid;

            }

            public void setUid(String uid) {

                this.uid = uid;

            }

            public String getUserIdName() {

                return userIdName;

            }

            public void setUserIdName(String userIdName) {

                this.userIdName = userIdName;

            }

        }

        java 對象與 json 字符串互轉換

        1. 本例使用 com.alibaba.fastjson.JSON

        2. 實體對象轉換為 json 字符串

        public static String toJSONString(Object city) {

        String jsonStr = "";

        if (city != null) {

        jsonStr = JSON.toJSONString(city);

        }

        return jsonStr;

        }

        3.json 字符串轉換為指定對象

        public static <T> T parseObject(String text, Class<T> clazz) {

                return JSON.parseObject(text, clazz);

            }

        4. 實體對象示例

        public class CityInfoModel implements Serializable {

        private static final long serialVersionUID = 4443714978780088961L;

        /** 城市名稱 */

        String cityName;

        /** 城市面積 */

        double landArea;

        /** 人口 */

        long population;

        /** 生產總值 */

        double gross ;

        /** 行政區劃代碼 */

        String areaNumber;

        /** 郵政編碼 */

        String postalCode;

        /** 電話區號 */

        String telephoneCode;

        /** 車牌代碼 */

        String carCode;

        /** 城市描述 */

        String cityDescribe;

        public String getCityName() {

        return cityName;

        }

        public void setCityName(String cityName) {

        this.cityName = cityName;

        }

        public double getLandArea() {

        return landArea;

        }

        public void setLandArea(double landArea) {

        this.landArea = landArea;

        }

        public long getPopulation() {

        return population;

        }

        public void setPopulation(long population) {

        this.population = population;

        }

        public double getGross() {

        return gross;

        }

        public void setGross(double gross) {

        this.gross = gross;

        }

        public String getAreaNumber() {

        return areaNumber;

        }

        public void setAreaNumber(String areaNumber) {

        this.areaNumber = areaNumber;

        }

        public String getPostalCode() {

        return postalCode;

        }

        public void setPostalCode(String postalCode) {

        this.postalCode = postalCode;

        }

        public String getTelephoneCode() {

        return telephoneCode;

        }

        public void setTelephoneCode(String telephoneCode) {

        this.telephoneCode = telephoneCode;

        }

        public String getCarCode() {

        return carCode;

        }

        public void setCarCode(String carCode) {

        this.carCode = carCode;

        }

        public String getCityDescribe() {

        return cityDescribe;

        }

        public void setCityDescribe(String cityDescribe) {

        this.cityDescribe = cityDescribe;

        }

        @Override

        public String toString() {

        return "CityModel [cityName=" + cityName

        +",landArea=" + landArea

        +",population=" + population

        +",gross=" + gross

        +",areaNumber=" + areaNumber

        +",postalCode=" + postalCode

        +",telephoneCode=" + telephoneCode

        +",carCode=" + carCode

        +",cityDescribe=" + cityDescribe

        +"]";

        }


        來自 “ ITPUB博客 ” ,鏈接:http://www.ep4tq.com/69946279/viewspace-2659648/,如需轉載,請注明出處,否則將追究法律責任。

        請登錄后發表評論 登錄
        全部評論
        管他誰是誰非,做自己的主宰,我是這條街最亮的崽!

        注冊時間:2019-08-22

        • 博文量
          49
        • 訪問量
          21835
        妹子图每日分享