java中jsonobject是什么,怎么使用呢?不知道的小伙伴來看看小編今天的分享吧!
1、JSONObject簡介:
JSONObject-lib包是一個beans,collections,maps,java arrays和xml和JSON互相轉(zhuǎn)換的包。
system:WIN7 myeclipse:6.5 tomcat:5.0 JDK:開發(fā)環(huán)境和編譯用的都是1.5。
項目結(jié)構(gòu)如下:
3、JSONObject:A JSONObject is an unordered collection of name/value pairs.是一個final類,繼承了Object,實現(xiàn)了JSON接口。
構(gòu)造方法如下:
JSONObject();創(chuàng)建一個空的JSONObject對象
JSONObject(boolean isNull);創(chuàng)建一個是否為空的JSONObject對象
普通方法如下:
fromBean(Object bean);靜態(tài)方法,通過一個pojo對象創(chuàng)建一個JSONObject對象
fromJSONObject(JSONObject object);靜態(tài)方法,通過另外一個JSONObject對象構(gòu)造一個JSONObject對象
fromJSONString(JSONString string);靜態(tài)方法,通過一個JSONString創(chuàng)建一個JSONObject對象
toString();把JSONObject對象轉(zhuǎn)換為json格式的字符串
iterator();返回一個Iterator對象來遍歷元素
接下來就是一些put/get方法,需要普通的get方法和pot方法做一下強(qiáng)調(diào)說明,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,實現(xiàn)了JSON接口。
構(gòu)造方法如下:
JSONArray();構(gòu)造一個空的JSONArray對象
普通方法如下:
fromArray(Object[] array);靜態(tài)方法,通過一個java數(shù)組創(chuàng)建一個JSONArray對象
fromCollection(Collection collection);靜態(tài)方法,通過collection集合對象創(chuàng)建一個JSONArray對象
fromString(String string);靜態(tài)方法,通過一個json格式的字符串構(gòu)造一個JSONArray對象
toString();把JSONArray對象轉(zhuǎn)換為json格式的字符串
iterator();返回一個Iterator對象來遍歷元素
接下來同樣是put/get方法……
5、XMLSerializer:Utility class for transforming JSON to XML an back.一個繼承自O(shè)bject的類
構(gòu)造方法如下:
XMLSerializer();創(chuàng)建一個XMLSerializer對象
普通方法如下:
setRootName(String rootName);設(shè)置轉(zhuǎn)換的xml的根元素名稱
setTypeHintsEnabled(boolean typeHintsEnabled);設(shè)置每個元素是否顯示type屬性
write(JSON json);把json對象轉(zhuǎn)換為xml,默認(rèn)的字符編碼是UTF-8,
需要設(shè)置編碼可以用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>
以上就是小編今天的分享了,希望可以幫助到大家。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com