zoukankan      html  css  js  c++  java
  • net.sf.json------json解析

    在测试终端支付时,发现net..sf.json.JSONArray;报红,引入了pom,项目里是jar包下载,不想复制移动一个个add to path,想用依赖的办法

    但还是报红色,原因是自动下载的包pom中没有指定版本号

    <dependency>
                <groupId>net.sf.json-lib</groupId>
                <artifactId>json-lib</artifactId>
                <version>2.4</version>
                <classifier>jdk15</classifier>
            </dependency>

    如果是gradle,引入:

    compile 'net.sf.json-lib:json-lib:2.4:jdk15'

    搞定,开始解析json

    看一下项目中的代码(解析见下)

    @SuppressWarnings("all")
        public static <T> List<T> json2List(String jsonstr,Class<T> cls){
            JSONArray ja = JSONArray.fromObject(jsonstr);
            List<T> list = JSONArray.toList(ja, cls);
            return list;
        }
    
        @SuppressWarnings("all")
        public static <T> T json2Obj(String jsonstr,Class<T> cls){
            JSONObject jo = JSONObject.fromObject(jsonstr);
            T obj = (T)JSONObject.toBean(jo, cls);
            return obj;
        }
    
        public static String obj2json(Object obj){
            return JSONObject.fromObject(obj).toString();
        }
    
        public static String array2json(Object obj){
            return JSONArray.fromObject(obj).toString();
        }
    
        public static <T1,T2> List<T2> convertMap2List(Map<T1,T2> map){
            if(map==null) return null;
            return new ArrayList<T2>(map.values());
        }

    首先我们知道

    JSON 和 JS 对象互转

    要实现从JSON字符串转换为JS对象,使用 JSON.parse() 方法:
    1
    var obj = JSON.parse('{"a": "Hello", "b": "World"}'); //结果是 {a: 'Hello', b: 'World'}
    要实现从JS对象转换为JSON字符串,使用 JSON.stringify() 方法:
    1
    var json = JSON.stringify({a: 'Hello', b: 'World'}); //结果是 '{"a": "Hello", "b": "World"}'

    而今天我们要用的就是一个json的帮助包之一的net.sf.json-,这些包其实都是类似的,帮我们封装了方法,直接使用

      其中jSONArray是一个一个加进去的;
             JSONObject是一对一对加进去的;

     1.JSONObject

      可以理解为是这个包里面的json类型是object就是最初始化的封装,并且给你封装了方法

      

    package com.itlwc.test;  
      
    import net.sf.json.JSONArray;  
    import net.sf.json.JSONObject;  
      
    public class Test {  
        public static void main(String[] args) {  
            // 创建JSONObject  
            JSONObject jsonObject = new JSONObject();  
            jsonObject.put("username", "lwc");  
            jsonObject.put("password", "123");  
            // 打印:1  
            System.out.println(jsonObject);  
      
            // 增加属性,打印:2  
            jsonObject.element("sex", "男");  
            System.out.println(jsonObject);  
              
            // 根据key返回,打印:3  
            System.out.println(jsonObject.get("sex"));  
      
            // 判读输出对象的类型  
            boolean isArray = jsonObject.isArray();  
            boolean isEmpty = jsonObject.isEmpty();  
            boolean isNullObject = jsonObject.isNullObject();  
            // 打印:4  
            System.out.println("是否数组:" + isArray + " 是否空:" + isEmpty + " 是否空对象:"  
                    + isNullObject);  
              
            // 把JSONArray增加到JSONObject中  
            JSONArray jsonArray = new JSONArray();  
            jsonArray.add(0, "lwc");  
            jsonArray.add(1, "nxj");  
            // 开始增加  
            jsonObject.element("student", jsonArray);  
            // 打印:5  
            System.out.println(jsonObject);  
        }  
    }  
    /* 
    打印结果 
        {"username":"lwc","password":"123"} 
        {"username":"lwc","password":"123","sex":"男"} 
        男 
        是否为数组:false 是否为空:false 是否为空对象:false 
        {"username":"lwc","password":"123","sex":"男","student":["lwc","nxj"]} 
    */  

      

    2.JSONArray(一般是一个一个加JSONObject)

      json数组的封装

      

    package com.itlwc.test;  
      
    import net.sf.json.JSONArray;  
    import net.sf.json.JSONObject;  
      
    public class Test {  
        public static void main(String[] args) {  
            //创建JSONArray  
            JSONArray jsonArray = new JSONArray();  
            jsonArray.add(0, "lwc");     
            jsonArray.add(1, "nxj");  
            jsonArray.element("mxj");  
            //打印:1  
            System.out.println(jsonArray);  
              
            //根据下标返回,打印:2  
            System.out.println(jsonArray.get(0));  
              
            //根据下标设置新值,打印:3  
            jsonArray.set(0, "itlwc");  
            System.out.println(jsonArray);  
              
            //把JSONObject放入到JSONArray中  
            JSONObject jsonObject = new JSONObject();  
            jsonObject.put("username", "lwc");  
            jsonObject.put("password", "123");  
            //开始增加,打印:4  
            jsonArray.add(jsonObject);  
            System.out.println(jsonArray);  
              
            //遍历,打印:5  
            for(int i=0;i<jsonArray.size();i++){  
                System.out.print(jsonArray.get(i)+"	");  
            }  
        }  
    }  
    /* 
    打印结果 
        ["lwc","nxj","mxj"] 
        lwc 
        ["itlwc","nxj","mxj"] 
        ["itlwc","nxj","mxj",{"username":"lwc","password":"123"}] 
        itlwc   nxj mxj {"username":"lwc","password":"123"} 

       3.JavaBean与json字符串互转 

    package com.itlwc.test;  
      
    import net.sf.json.JSONObject;  
      
    import com.itlwc.entity.Student;  
      
    public class Test {  
        public static void main(String[] args) {  
            // JavaBean对象转json字符串  
            Student stu1 = new Student("lwc", "111111");  
            JSONObject jsonObject = JSONObject.fromObject(stu1);  
            System.out.println(jsonObject);  
      
            // json字符串转JavaBean  
            String jsondata = "{"password":"111111","username":"lwc"}";  
            JSONObject jsonObject1 = JSONObject.fromObject(jsondata);  
            Student stu2 = (Student) JSONObject.toBean(jsonObject1, Student.class);  
            System.out.println(stu2);  
        }  
    }  
    /* 
    打印结果: 
        {"password":"111111","username":"lwc"} 
        用户: lwc 密码:111111 
    */  

      4.List与json字符串互转

    package com.itlwc.test;  
      
    import java.util.ArrayList;  
    import java.util.List;  
      
    import net.sf.json.JSONArray;  
    import net.sf.json.JSONObject;  
      
    import com.itlwc.entity.Student;  
      
    public class Test {  
        public static void main(String[] args) {  
            // List转json字符串  
            List list = new ArrayList();  
            list.add(new Student("lwc", "111111"));  
            list.add(new Student("nxj", "222222"));  
            JSONArray jsonArray = JSONArray.fromObject(list);  
            System.out.println(jsonArray);  
      
            // json字符串转List  
            List list1 = new ArrayList();  
            String jsondata = "[{"password":"111111","username":"lwc"},{"password":"222222","username":"nxj"}]";  
            JSONArray jsonArray1 = JSONArray.fromObject(jsondata);  
            for (int i = 0; i < jsonArray1.size(); i++) {  
                JSONObject jsonObject2 = jsonArray1.getJSONObject(i);  
                Student stu2 = (Student) JSONObject.toBean(jsonObject2,  
                        Student.class);  
                list1.add(stu2);  
            }  
            System.out.println(list1);  
        }  
    }  
    /* 
    打印结果: 
        [{"password":"111111","username":"lwc"},{"password":"222222","username":"nxj"}] 
        [用户: lwc 密码:111111, 用户: nxj 密码:222222] 

      5.Map与json字符串互转

    package com.itlwc.test;  
      
    import java.util.HashMap;  
    import java.util.Iterator;  
    import java.util.Map;  
    import java.util.Set;  
      
    import net.sf.json.JSONObject;  
      
    import com.itlwc.entity.Student;  
      
    public class Test {  
        public static void main(String[] args) {  
            // Map转json字符串  
            Map map = new HashMap();  
            map.put("1", new Student("lwc", "111111"));  
            map.put("2", new Student("nxj", "222222"));  
            JSONObject jsonMap = JSONObject.fromObject(map);  
            System.out.println(jsonMap);  
      
            // json字符串转Map  
            String jsondata = "{"2":{"password":"222222","username":"nxj"},"1":{"password":"111111","username":"lwc"}}";  
            Map map1 = (Map) JSONObject.fromObject(jsondata);  
            Set set = map1.keySet();  
            Iterator ite = set.iterator();  
            while (ite.hasNext()) {  
                String key = (String) ite.next();  
                JSONObject jsonObject = JSONObject.fromObject(map1.get(key));  
                Student stu = (Student) JSONObject  
                        .toBean(jsonObject, Student.class);  
                System.out.println(key + " " + stu);  
            }  
      
        }  
    }  
    /* 
    打印结果:  
        {"2":{"password":"222222","username":"nxj"},"1":{"password":"111111","username":"lwc"}} 
        2 用户: nxj 密码:222222 
        1 用户: lwc 密码:111111 

      

      6.JSONArray与List互转

    package com.itlwc.test;  
      
    import java.util.ArrayList;  
    import java.util.Iterator;  
    import java.util.List;  
      
    import net.sf.json.JSONArray;  
    import net.sf.json.JsonConfig;  
      
    import com.itlwc.entity.Student;  
      
    public class Test {  
        public static void main(String[] args) {  
            //List转型JSONArray  
            List<Student> list = new ArrayList<Student>();    
            list.add(new Student("lwc", "111111"));  
            list.add(new Student("nxj", "222222"));   
            JSONArray jsonArray = JSONArray.fromObject(list);  
            System.out.println(jsonArray.toString());  
              
            //JSONArray转型List  
            List<Student> list2 = JSONArray.toList(jsonArray, new Student(), new JsonConfig());  
            Iterator<Student> ite =  list2.iterator();  
            while(ite.hasNext()){  
                Student stu =ite.next();  
                System.out.println(stu);  
            }  
        }  
    }  
    /* 
    打印结果 
        [{"password":"111111","username":"lwc"},{"password":"222222","username":"nxj"}] 
        用户: lwc 密码:111111 
        用户: nxj 密码:222222 

     7.JSONArray与数组互转

      

    package com.itlwc.test;  
      
    import net.sf.json.JSONArray;  
      
    public class Test {  
        public static void main(String[] args) {  
            // Java数组转JSONArray  
            boolean[] boolArray = new boolean[] { true, false, true };  
            JSONArray jsonArray = JSONArray.fromObject(boolArray);  
            System.out.println(jsonArray.toString());  
      
            // JSONArray转Java数组  
            Object obj[] = jsonArray.toArray();  
            for (Object o : obj) {  
                System.out.print(o + " ");  
            }  
        }  
    }  
    /* 
    打印结果 : 
        [true,false,true] 
        true false true  

    8.XML与JSON互转

    需要导入xom-1.1.jar

    package com.itlwc.test;  
      
    import net.sf.json.JSON;  
    import net.sf.json.JSONObject;  
    import net.sf.json.xml.XMLSerializer;  
      
    public class Test {  
        public static void main(String[] args) throws Exception {  
            // XML转JSON  
            String xml = "<root>" + "<name type='type'>zhaipuhong</name>"  
                    + "<gender>male</gender>" + "<birthday>" + "<year>1970</year>"  
                    + "<month>12</month>" + "<day>17</day>" + "</birthday>"  
                    + "</root>";  
            XMLSerializer xmlSerializer = new XMLSerializer();  
            JSON json = xmlSerializer.read(xml);  
            System.out.println(json.toString(2));  
      
            // JSON转XML  
            String jsondata = "{"root":{" + ""name":"zhaipuhong","  
                    + ""gender":"male"," + ""birthday":{"  
                    + ""year":"1970"," + ""month":"12"," + ""day":"17""  
                    + "}" + "}" + "}";  
            JSONObject jsonObject = JSONObject.fromObject(jsondata);  
            String xmlstr = new XMLSerializer().write(jsonObject);  
            System.out.println(xmlstr);  
        }  
    }  
    /* 
    打印结果: 
        { 
          "name": "zhaipuhong", 
          "gender": "male", 
          "birthday":   { 
            "year": "1970", 
            "month": "12", 
            "day": "17" 
          } 
        } 
        <?xml version="1.0" encoding="UTF-8"?> 
        <o> 
            <root class="object"> 
                <birthday class="object"> 
                    <day type="string">17</day> 
                    <month type="string">12</month> 
                    <year type="string">1970</year> 
                </birthday> 
                <gender type="string">male</gender> 
                <name type="string">zhaipuhong</name> 
            </root> 
        </o> 
    */  
  • 相关阅读:
    Delphi Help
    RAD 10 新控件 TSearchBox TSplitView
    滚动条
    c++builder Active Form
    chart左侧
    RAD 10 蓝牙
    浏览器插件 火狐插件
    c++builder delphi 调用dll dll编写
    模拟键盘 键盘虚拟代码
    oracle怎么把一个用户下的表复制给另一个用户?(授予表权限)
  • 原文地址:https://www.cnblogs.com/yangj-Blog/p/13091356.html
Copyright © 2011-2022 走看看