JSONArray 和JSONObject的应用
参考文献: http://www.52php.cn/article/p-dgmuwtms-cd.html 1.JAR包简介要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包:
2.JSONObject对象使用JSON-lib包是一个beans,collections,maps,java arrays 和XML和JSON互相转换的包。在本例中,我们将使用JSONObject类创建JSONObject对象,然后我们打印这些对象的值。为了使用JSONObject对象,我们要引入"net.sf.json"包。为了给对象添加元素,我们要使用put()方法。 2.1.实例1package jsontest; 输出结果 jsonObject:{"username":"huangwuyi","nickname":"梦中心境"} 是否为数组:false, 是否为空:false, isNullObject:false 添加属性后的对象:{"username":"huangwuyi","address":"福建省厦门市"} {"username":"huangwuyi","another jsonArray value"]} 返回一个JSONArray对象:["this is a jsonArray value","another jsonArray value"] 结果={"username":"huangwuyi","another jsonArray value"]} username==>huangwuyi qq=413425430 2.2.实例2.package jsontest; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JSONTest { public static void main(String args[]) { JSONObject jsonObj0 = new JSONObject(); JSONObject jsonObj = new JSONObject(); JSONObject jsonObj2 = new JSONObject(); JSONObject jsonObj3 = new JSONObject(); JSONArray jsonArray = new JSONArray(); //创建jsonObj0 jsonObj0.put("name0","zhangsan"); jsonObj0.put("sex1","female"); System.out.println("jsonObj0:"+jsonObj0); //创建jsonObj1 jsonObj.put("name","xuwei"); jsonObj.put("sex","male"); System.out.println("jsonObj:"+jsonObj); //创建jsonObj2,包含两个条目,条目内容分别为jsonObj0,jsonObj1 jsonObj2.put("item0",jsonObj0); jsonObj2.put("item1",jsonObj); System.out.println("jsonObj2:"+jsonObj2); //创建jsonObj3,只有一个条目,内容为jsonObj2 jsonObj3.element("j3",jsonObj2); System.out.println("jsonObj3:"+jsonObj3); //往JSONArray中添加JSONObject对象。发现JSONArray跟JSONObject的区别就是JSONArray比JSONObject多中括号[] jsonArray.add(jsonObj); System.out.println("jsonArray:"+jsonArray); JSONObject jsonObj4 = new JSONObject(); jsonObj4.element("weather",jsonArray); System.out.println("jsonObj4:"+jsonObj4); } } 输出结果: jsonObj0:{"name0":"zhangsan","sex1":"female"} jsonObj:{"name":"xuwei","sex":"male"} jsonObj2:{"item0":{"name0":"zhangsan","sex1":"female"},"item1":{"name":"xuwei","sex":"male"}} jsonObj3:{"j3":{"item0":{"name0":"zhangsan","sex":"male"}}} jsonArray:[{"name":"xuwei","sex":"male"}] jsonObj4:{"weather":[{"name":"xuwei","sex":"male"}]} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |