1、JSONObject簡介:
JSONObject-lib包是一個beans,collections,maps,java arrays和xml和JSON互相轉換的包。
2、專案環境:
system:win7 myeclipse:6.5 tomcat:5.0 JDK:開發環境和編譯用的都是1.5。
專案結構如下:
3、JSONObject:A JSONObject is an unordered collection of name/value pairs.是一個final類,繼承了Object,實現了JSON介面。
構造方法如下:
JSONObject();建立一個空的JSONObject物件
JSONObject(boolean isNull);建立一個是否為空的JSONObject物件
普通方法如下:
fromBean(Object bean);靜態方法,通過一個pojo物件建立一個JSONObject物件
fromJSONObject(JSONObject object);靜態方法,通過另外一個JSONObject物件構造一個JSONObject物件
fromJSONString(JSONString string);靜態方法,通過一個JSONString建立一個JSONObject物件
toString();把JSONObject物件轉換為json格式的字串
iterator();返回一個Iterator物件來遍歷元素
接下來就是一些put/get方法,需要普通的get方法和pot方法做一下強調說明,API中是這樣描述的:
A get method returns a value if one can be found, and throws an exception if one cannot be found. An opt method returns a default value instead of throwing an exception, and so is useful for obtaining optional values.
4、JSONArray:A JSONArray is an ordered sequence of values.是一個final類,繼承了Object,實現了JSON介面。
構造方法如下:
JSONArray();構造一個空的JSONArray物件
普通方法如下:
fromArray(Object[] array);靜態方法,通過一個java陣列建立一個JSONArray物件
fromCollection(Collection collection);靜態方法,通過collection集合物件建立一個JSONArray物件
fromString(String string);靜態方法,通過一個json格式的字串構造一個JSONArray物件
toString();把JSONArray物件轉換為json格式的字串
iterator();返回一個Iterator物件來遍歷元素
接下來同樣是put/get方法……
5、XMLSerializer:Utility class for transforming JSON to XML an back.一個繼承自Object的類
構造方法如下:
XMLSerializer();建立一個XMLSerializer物件
普通方法如下:
setRootName(String rootName);設定轉換的xml的根元素名稱
setTypeHintsEnabled(boolean typeHintsEnabled);設定每個元素是否顯示type屬性
write(JSON json);把json物件轉換為xml,預設的字元編碼是UTF-8,
需要設定編碼可以用write(JSON json, String encoding)
對XML和JSON字串各列一個簡單的例子:
JSON:
{"password":"123456","username":"張三"}
xml
<?xml version="1.0" encoding="UTF-8"?>
<user_info>
<password>123456</password>
<username>張三</username>
</user_info>