JSONObject與JSONArray的使用html
1、JAR包簡單介紹java
要使程序可以執行必須引入JSON-lib包,JSON-lib包同一時候依賴於下面的JAR包:json
1.commons-lang.jarapi
2.commons-beanutils.jarthis
3.commons-collections.jarspa
4.commons-logging.jar .net
5.ezmorph.jarhtm
6.json-lib-2.2.2-jdk15.jar對象
2、JSONObject對象使用element
JSON-lib包是一個beans,collections,maps,java arrays 和XML和JSON互相轉換的包。在本例中,咱們將使用JSONObject類建立JSONObject對象,而後咱們打印這些對象的值。爲了使用JSONObject對象,咱們要引入"net.sf.json"包。爲了給對象加入元素,咱們要使用put()方法。
package com.hwy;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JSONObjectSample {
//建立JSONObject對象
private static JSONObject createJSONObject(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","huangwuyi");
jsonObject.put("sex", "男");
jsonObject.put("QQ", "999999999");
jsonObject.put("Min.score", new Integer(99));
jsonObject.put("nickname", "夢中心境");
return jsonObject;
}
public static void main(String[] args) {
JSONObject jsonObject = JSONObjectSample.createJSONObject();
//輸出jsonobject對象
System.out.println("jsonObject==>"+jsonObject);
//判讀輸出對象的類型
boolean isArray = jsonObject.isArray();
boolean isEmpty = jsonObject.isEmpty();
boolean isNullObject = jsonObject.isNullObject();
System.out.println("isArray:"+isArray+" isEmpty:"+isEmpty+" isNullObject:"+isNullObject);
//加入屬性
jsonObject.element("address", "福建省廈門市");
System.out.println("加入屬性後的對象==>"+jsonObject);
//返回一個JSONArray對象
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, "this is a jsonArray value");
jsonArray.add(1,"another jsonArray value");
jsonObject.element("jsonArray", jsonArray);
JSONArray array = jsonObject.getJSONArray("jsonArray");
System.out.println("返回一個JSONArray對象:"+array);
//加入JSONArray後的值
// {"username":"huangwuyi","sex":"男","QQ":"999999999","Min.score":99,"nickname":"夢中心境","address":"福建省廈門市","jsonArray":["this is a jsonArray value","another jsonArray value"]}
System.out.println("結果="+jsonObject);
//依據key返回一個字符串
String username = jsonObject.getString("username");
System.out.println("username==>"+username);
//把字符轉換爲 JSONObject
String temp=jsonObject.toString();
JSONObject object = JSONObject.fromObject(temp);
//轉換後依據Key返回值
System.out.println("qq="+object.get("QQ"));
}
}
JSONObject 在線API:http://json-lib.sourceforge.net/apidocs/jdk15/index.html