JSONObject

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"]}
    */

JSONArray

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)+"\t");
            }
        }
    }
    /*
    打印结果
        ["lwc","nxj","mxj"]
        lwc
        ["itlwc","nxj","mxj"]
        ["itlwc","nxj","mxj",{"username":"lwc","password":"123"}]
        itlwc    nxj    mxj    {"username":"lwc","password":"123"}
    */

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
    */

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]
    */

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
    */

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
    */

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
    */

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>
    */

net.sf.json的更多相关文章

  1. net.sf.json.JSONException: There is a cycle in the hierarchy!的解决办法

    使用Hibernate manytoone属性关联主表的时候,如果使用JSONArray把pojo对象转换成json对象时,很容易出现循环的异常.解决的办法就是, 在转换json对象时忽略manyto ...

  2. Json_异常_net.sf.json.JSONException: JSONObject["solution"] not found.

    net.sf.json.JSONException: JSONObject["solution"] not found. 没有这个元素造成的. 问题代码: JSONObject j ...

  3. 使用JSONObject遇到的问题,java.lang.NoClassDefFoundError: net/sf/json/JSONObject

    先是报 java.lang.NoClassDefFoundError: net/sf/json/JSONObject 这个错误, 打开项目属性找到java build path中的libaries,找 ...

  4. Net.Sf.Json java Object to JsonObject

    public class People{ private String name; public void setName(String name){ this.name = name; } publ ...

  5. java.lang.ClassNotFoundException: net.sf.json.JSONArray,java.lang.NoClassDefFoundError: net/sf/json/JSONArray jetty跑项目遇到的问题

    2016-05-18 15:44:25 ERROR Dispatcher.error[user:|url:]:L38 - Dispatcher initialization failed Unable ...

  6. net.sf.json 时间格式的转化

    后台代码 //后台代码 response.setCharacterEncoding("UTF-8"); JsonConfig jsonConfig = new JsonConfig ...

  7. net.sf.json.JSONObject 和org.json.JSONObject 的差别

    http://my.oschina.net/wangwu91/blog/340721 net.sf.json.JSONObject 和org.json.JSONObject  的差别. 一.创建jso ...

  8. atitit.解决net.sf.json.JSONException There is a cycle in the hierarchy

    atitit.解决net.sf.json.JSONException There is a cycle in the hierarchy 1. 环境:使用hibernate4跟个,,要不个哪的对象系列 ...

  9. net.sf.json.JSONException: java.lang.NoSuchMethodException

    在尝试将json对象转换为list时候出现了如下错误 Exception in thread "main" net.sf.json.JSONException: java.lang ...

  10. net.sf.json.JSONException: Object is null

    出现这个错误的原因是net.sf.json.JSONArray或JSONObject转换时,对象内包含另一个对象,而该被包含的对象为NULL,所以抛出异常. 补充: 最可恨的是,明明转换的时候已经成功 ...

随机推荐

  1. ios 当margin-left margin-right 超过设备宽度

    ios 当margin-left  margin-right过长,相加超过  超过设备宽度时,导致页面不能上下滚动,目前尚未找到解决办法,记录一下

  2. 三大前端框架(react、vue、angular2+)父子组件通信总结

    公司业务需要,react.vue.angular都有接触[\无奈脸].虽然说可以拓展知识广度,但是在深度上很让人头疼.最近没事的时候回忆各框架父子组件通信,发现很模糊,于是乎稍微做了一下功课,记录于此 ...

  3. 20165313 《网络对抗技术》 Kali安装

    一.目的要求 下载 安装 网络 共享 软件源 二.主要步骤 我主要是按照最新超详细虚拟机VMware安装Kali Linux 这个方法做的就没有步骤描述了. 安装结果图: 注意事项 安装过程中如果没有 ...

  4. 学习笔记CB012: LSTM 简单实现、完整实现、torch、小说训练word2vec lstm机器人

    真正掌握一种算法,最实际的方法,完全手写出来. LSTM(Long Short Tem Memory)特殊递归神经网络,神经元保存历史记忆,解决自然语言处理统计方法只能考虑最近n个词语而忽略更久前词语 ...

  5. 关于符号匹配题的一些思考过程--含cin.getline()函数的一些基本原理

    刚刚拿到题目的时候,还没啥感觉,就是觉得要用到if--else就可以了,但是一联想到现在是在学栈,那么是不是要用到栈呢? 一.那么先看看题目吧 给定一串字符,不超过100个字符,可能包括括号.数字.字 ...

  6. 【mysql-server】遇到的坑

    一.前提 最近因为工作原因,不得不用windows电脑,发现windows装mysql真的坑太多 23333: 二.环境 windows 环境 mysql 5.7(不建议用5.8坑更多) 三.步骤 3 ...

  7. CS萌新的汇编学习之路(其实是老师作业呵呵哒)Learning of Assembly Language

    第一节课学习汇编语言,做笔记,做笔记 1.概念 首先是汇编语言这门课程的定义以及对于学习高级语言.深入理解计算机系统的作用 软硬件接口机器语言 汇编语言 高级语言 关系 机器语言和汇编语言可移植性差 ...

  8. gradle 打包springboot项目,找不到项目jar application.class

    如题:gradle 打包springboot项目,找不到项目jar入口main方法:application.class 检查:lib/目录下没有相应项目的jar包 用gradle命令行查看日志:gra ...

  9. 【SQL实践】其他常用SQL汇总

    [SQL实践]其他常用SQL汇总 1.联表更新 update students stu inner join course on course.STUDENT_ID=stu.id set stu.na ...

  10. 基于嵌入式linux路由转发功能的实现

    环境 arm7开发板, uclinux系统,kernel version: linux-2.4.x arm芯片的单网卡双网口设备,eth0 WAN口 ipaddr 192.168.9.61 eth0: ...