zoukankan      html  css  js  c++  java
  • Json与bean的相互转换

    本文使用json-lib jar包实现Json与bean的相互转换

    1.将字符串转为JSON

    使用JSONObject.fromObject(str)方法即可将字符串转为JSON对象

    使用JSONObject.put("attribute","value")可为JSON添加属性

    如果需要转为JSON数组,只需使用JSONArray对象提供的方法即可

    /** 
       * 一些简单的转换 
       */  
      public static void transformStringTest() {  
          String str = "{" + ""id":" + ""1"," + ""name":" + ""zhangsan""  
                  + "}";  
          //1.将字符串转为JSON  
          JSONObject jsonObj = JSONObject.fromObject(str);  
          System.out.println(jsonObj.toString());  
          //JSON添加属性  
          jsonObj.put("age", "22");  
          System.out.println(jsonObj.toString());  
          //2.将对象转为数组  
          JSONArray jsonArr = JSONArray.fromObject(jsonObj);  
          System.out.println(jsonArr.toString());  
          //3.将数组添加到JSON对象中  
          JSONObject obj = new JSONObject();  
          obj.put("employees", jsonArr);  
          System.out.println(obj.toString());  
      }  
    /* 输出内容 
     * {"id":"1","name":"zhangsan"}  
     * {"id":"1","name":"zhangsan","age":"22"} 
     * [{"id":"1","name":"zhangsan","age":"22"}] 
     * {"employees":[{"id":"1","name":"zhangsan","age":"22"}]} 
     */  

    2.将对象转为JSON

    首先创建People类

    public class People {  
        private String name;  
      
        private String idcard;  
      
        public People() {  
        }  
      
        public People(String name, String idcard) {  
            this.name = name;  
            this.idcard = idcard;  
        }  
      
        public String getName() {  
            return name;  
        }  
      
        public void setName(String name) {  
            this.name = name;  
        }  
      
        public String getIdcard() {  
            return idcard;  
        }  
      
        public void setIdcard(String idcard) {  
            this.idcard = idcard;  
        }  
      
    } 

    将对象转为JSON同样使用SONObject.fromObject(obj)方法

    如果是一个List,转为JSON时需要使用JSONArray将对象转为JSON数组

    public static void transformObjectTest() {  
            People p1 = new People("a", "111111");  
            //1.将对象转为json  
            System.out.println(JSONObject.fromObject(p1));  
            List<People> peopleList = new ArrayList<People>();  
            peopleList.add(p1);  
            //2.将list转为json(需要使用数组JSONArray)  
            JSONArray arr = JSONArray.fromObject(peopleList);  
            System.out.println(arr.toString());  
        }   
    
    /*输出内容 
        * {"idcard":"111111","name":"a"}  
        * [{"idcard":"111111","name":"a"}] 
        */ 

    3.JSON转为bean

    json转为bean的方法也非常简单,只需使用JSONObject.toBean()方法即可,使用该方法的时候需要传入Bean的class

    /** 
         * 将json转换为bean 
         * @param json 
         * @param type 
         * @return 
         */  
        public static <T> Object transformJsonToBean(String json, Class<T> type) {  
            JSONObject jsonObject = JSONObject.fromObject(json);  
            return JSONObject.toBean(jsonObject, type);  
        }  

    4.JSON转为list<bean>集合

    由于是集合,所以需要使用JSONArray,JSONArray提供了toCollection方法,使用该方法同样需要传入bean的class

    public static <T> Object transformJsonToBeanList(String jsonArr,  
               Class<T> type) {  
           JSONArray jsonArray = JSONArray.fromObject(jsonArr);  
           return JSONArray.toCollection(jsonArray, type);  
       }  
     
     
    /**  
     * 项目名称:tools  
     * 项目包名:com.songfayuantools.json  
     * 创建时间:2017年7月31日上午11:58:51  
     * 创建者:Administrator-宋发元  
     * 创建地点:  
     */  
    package com.songfayuantools.json;  
      
    import com.songfayuantools.entity.UserInfo;  
      
    import net.sf.json.JSON;  
    import net.sf.json.JSONObject;  
    import net.sf.json.xml.XMLSerializer;  
      
    /**  
     * 描述:JSONObject使用方法详解  
     *     JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包。  
     * @author songfayuan  
     * 2017年7月31日上午11:58:51  
     */  
    public class Json {  
      
        /**  
         * 描述:json字符串转java代码  
         * @author songfayuan  
         * 2017年8月2日下午2:24:47  
         */  
        public static void jsonToJava() {  
            System.out.println("json字符串转java代码");  
            String jsonStr = "{"password":"123456","username":"张三"}";  
            JSONObject jsonObject = JSONObject.fromObject(jsonStr);  
            String username = jsonObject.getString("username");  
            String password = jsonObject.getString("password");  
            System.err.println("json--->java 
     username="+username+"	 passwor="+password);  
        }  
          
        /**  
         * 描述:java代码封装为json字符串  
         * @author songfayuan  
         * 2017年8月2日下午2:30:58  
         */  
        public static void javaToJSON() {  
            System.out.println("java代码封装为json字符串");  
            JSONObject jsonObject = new JSONObject();  
            jsonObject.put("username", "宋发元");  
            jsonObject.put("age", 24);  
            jsonObject.put("sex", "男");  
            System.out.println("java--->json 
     " + jsonObject.toString());  
        }  
          
        /**  
         * 描述:json字符串转xml字符串  
         * @author songfayuan  
         * 2017年8月2日下午2:56:30  
         */  
        public static void jsonToXML() {  
            System.out.println("json字符串转xml字符串");  
            String jsonStr = "{"username":"宋发元","password":"123456","age":"24"}";  
            JSONObject jsonObject = JSONObject.fromObject(jsonStr);  
            XMLSerializer xmlSerializer = new XMLSerializer();  
            xmlSerializer.setRootName("user_info");  
            xmlSerializer.setTypeHintsEnabled(false);  
            String xml = xmlSerializer.write(jsonObject);  
            System.out.println("json--->xml 
    " + xml);  
        }  
          
        /**  
         * 描述:xml字符串转json字符串  
         * @author songfayuan  
         * 2017年8月2日下午3:19:25  
         */  
        public static void xmlToJSON() {  
            System.out.println("xml字符串转json字符串");  
            String xml = "<?xml version="1.0" encoding="UTF-8"?><user_info><password>123456</password><username>宋发元</username></user_info>";  
            XMLSerializer xmlSerializer = new XMLSerializer();  
            JSON json = xmlSerializer.read(xml);  
            System.out.println("xml--->json 
    " + json.toString());  
        }  
          
        /**  
         * 描述:javaBean转json字符串  
         * @author songfayuan  
         * 2017年8月2日下午3:39:10  
         */  
        public static void javaBeanToJSON() {  
            System.out.println("javaBean转json字符串");  
            UserInfo userInfo = new UserInfo();  
            userInfo.setUsername("宋发元");  
            userInfo.setPassword("123456");  
            JSONObject jsonObject = JSONObject.fromObject(userInfo);  
            System.out.println("JavaBean-->json 
    " + jsonObject.toString());  
        }  
          
        /**  
         * 描述:javaBean转xml字符串  
         * @author songfayuan  
         * 2017年8月2日下午3:48:08  
         */  
        public static void javaBeanToXML() {  
            System.out.println("javaBean转xml字符串");  
            UserInfo userInfo = new UserInfo();  
            userInfo.setUsername("songfayuan");  
            userInfo.setPassword("66666");  
            JSONObject jsonObject = JSONObject.fromObject(userInfo);  
            XMLSerializer xmlSerializer = new XMLSerializer();  
            String xml = xmlSerializer.write(jsonObject, "UTF-8");  
            System.out.println("javaBean--->xml 
    " + xml);  
        }  
          
        public static void main(String args[]) {  
    //      jsonToJava();  
    //      javaToJSON();  
    //      jsonToXML();  
    //      xmlToJSON();  
    //      javaBeanToJSON();  
            javaBeanToXML();  
        }  
          
    }  
  • 相关阅读:
    【洛谷5304】[GXOI/ZOI2019] 旅行者(二进制分组+最短路)
    【LOJ6485】LJJ 学二项式定理(单位根反演)
    【CF932E】Team Work(第二类斯特林数简单题)
    【CF960G】Bandit Blues(第一类斯特林数)
    【洛谷4689】[Ynoi2016] 这是我自己的发明(莫队)
    【洛谷5355】[Ynoi2017] 由乃的玉米田(莫队+bitset)
    【洛谷5268】[SNOI2017] 一个简单的询问(莫队)
    【洛谷4688】[Ynoi2016] 掉进兔子洞(莫队+bitset)
    【洛谷3653】小清新数学题(数论)
    【洛谷6626】[省选联考 2020 B 卷] 消息传递(点分治基础题)
  • 原文地址:https://www.cnblogs.com/icebutterfly/p/9009632.html
Copyright © 2011-2022 走看看