JSONObject使用方法

1.JSONObject介紹

JSONObject-lib包是一個beans,collections,maps,java arrays和xml和JSON互相轉換的包。html

2.下載jar包

http://files.cnblogs.com/java-pan/lib.rarjava

提供了除JSONObject的jar以外依賴的其餘6個jar包,一共7個jar文件web

說明:由於工做中項目用到的版本是1.1的對應jdk1.3的版本,故本篇博客是基於1.1版本介紹的。apache

對應此版本的javadoc下載路徑以下:http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-1.1/json

目前最新的版本爲2.4,其餘版本下載地址爲http://sourceforge.net/projects/json-lib/files/json-lib/api

3.項目環境:

system:WIN7 myeclipse:6.5 tomcat:5.0 JDK:開發環境和編譯用的都是1.5數組

項目結構以下:tomcat

說明本次用到的的文件只有工程目錄json包下的JSONObject_1_3類和note.txteclipse

4.class&method 基於1.1的API

作如下幾點約定:測試

1.介紹基於JSONObject 1.1的API

2.只介紹經常使用的類和方法

3.再也不介紹此版本中已經再也不推薦使用

4.介紹的類和方法主要圍繞本篇博客中用到的

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方法和put方法作一下強調說明,API中是這樣描述的:

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.


‍‍‍ 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方法……

 

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)

5.對XML和JSON字符串各列一個簡單的例子

JSON:
{"password":"123456","username":"張三"}
xml
<?xml version="1.0" encoding="UTF-8"?> <user_info>
<password>123456</password>
<username>張三</username>
</user_info>

start

新建web工程,工程名稱JS,導入如下7個jar包,文件在前面的準備工做中下載路徑。

說明能夠不用新建web工程,普通的java工程也能夠完成本篇的的操做。至於爲何要導入處json包之外的其餘6個包,我會把note.txt貼在最後,各位一看便知。

問題1:後臺接受到前臺的json格式的字符串怎麼處理?

 public static void jsonToJAVA() {
 System.out.println("json字符串轉java代碼");
 String jsonStr = "{\"password\":\"123456\",\"username\":\"張三\"}";
 JSONObject jsonObj = JSONObject.fromString(jsonStr);
 String username = jsonObj.getString("username");
 String password = jsonObj.optString("password");
 System.out.println("json--->java\n username=" + username
 + "\t password=" + password);
 }

顯示:

問題2:後臺是怎麼拼裝json格式的字符串?

public static void javaToJSON() {
2 System.out.println("java代碼封裝爲json字符串");
3 JSONObject jsonObj = new JSONObject();
4 jsonObj.put("username", "張三");
5 jsonObj.put("password", "123456");
6 System.out.println("java--->json \n" + jsonObj.toString());
7 }

顯示:

問題3:json格式的字符串怎麼轉換爲xml格式的字符串?

public static void jsonToXML() {
System.out.println("json字符串轉xml字符串");
String jsonStr = "{\"password\":\"123456\",\"username\":\"張三\"}";
JSONObject json = JSONObject.fromString(jsonStr);
XMLSerializer xmlSerializer = new XMLSerializer();
xmlSerializer.setRootName("user_info");
xmlSerializer.setTypeHintsEnabled(false);
String xml = xmlSerializer.write(json);
System.out.println("json--->xml \n" + xml);
}

顯示:

問題4:xml格式的字符串怎麼轉換爲json格式的字符串?

public static void xmlToJSON(){
System.out.println("xml字符串轉json字符串");
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user_info><password>123456</password><username>張三</username></user_info>";
JSON json=XMLSerializer.read(xml);
System.out.println("xml--->json \n"+json.toString());
}

顯示:

問題5:javabean怎麼轉換爲json字符串?

public static void javaBeanToJSON() {
System.out.println("javabean轉json字符串");
UserInfo userInfo = new UserInfo();
userInfo.setUsername("張三");
userInfo.setPassword("123456");
JSONObject json = JSONObject.fromBean(userInfo);
System.out.println("javabean--->json \n" + json.toString());
}

顯示:

問題6:javabean怎麼轉換爲xml字符串?

public static void javaBeanToXML() {
 System.out.println("javabean轉xml字符串");
 UserInfo userInfo = new UserInfo();
 userInfo.setUsername("張三");
 userInfo.setPassword("123456");
 JSONObject json = JSONObject.fromBean(userInfo);
 XMLSerializer xmlSerializer = new XMLSerializer();
 String xml = xmlSerializer.write(json, "UTF-8");
 System.out.println("javabean--->xml \n" + xml);
}

顯示:

 

完整的JSONObject_1_3.java代碼以下:

JSONObject_1_3
package json;

import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

public class JSONObject_1_3 {
public static void javaToJSON() {
System.out.println("java代碼封裝爲json字符串");
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", "張三");
jsonObj.put("password", "123456");
System.out.println("java--->json \n" + jsonObj.toString());
}

public static void jsonToJAVA() {
System.out.println("json字符串轉java代碼");
String jsonStr = "{\"password\":\"123456\",\"username\":\"張三\"}";
JSONObject jsonObj = JSONObject.fromString(jsonStr);
String username = jsonObj.getString("username");
String password = jsonObj.optString("password");
System.out.println("json--->java\n username=" + username
+ "\t password=" + password);
}

public static void jsonToXML() {
System.out.println("json字符串轉xml字符串");
String jsonStr = "{\"password\":\"123456\",\"username\":\"張三\"}";
JSONObject json = JSONObject.fromString(jsonStr);
XMLSerializer xmlSerializer = new XMLSerializer();
xmlSerializer.setRootName("user_info");
xmlSerializer.setTypeHintsEnabled(false);
String xml = xmlSerializer.write(json);
System.out.println("json--->xml \n" + xml);
}

public static void javaBeanToJSON() {
System.out.println("javabean轉json字符串");
UserInfo userInfo = new UserInfo();
userInfo.setUsername("張三");
userInfo.setPassword("123456");
JSONObject json = JSONObject.fromBean(userInfo);
System.out.println("javabean--->json \n" + json.toString());
}

public static void javaBeanToXML() {
System.out.println("javabean轉xml字符串");
UserInfo userInfo = new UserInfo();
userInfo.setUsername("張三");
userInfo.setPassword("123456");
JSONObject json = JSONObject.fromBean(userInfo);
XMLSerializer xmlSerializer = new XMLSerializer();
String xml = xmlSerializer.write(json, "UTF-8");
System.out.println("javabean--->xml \n" + xml);
}

public static void xmlToJSON(){
System.out.println("xml字符串轉json字符串");
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user_info><password>123456</password><username>張三</username></user_info>";
JSON json=XMLSerializer.read(xml);
System.out.println("xml--->json \n"+json.toString());
}

public static void main(String args[]) {
// javaToJSON();
// jsonToJAVA();
// jsonToXML();
// javaBeanToJSON();
// javaBeanToXML();
xmlToJSON();
}
}

完整的UserInfo.java代碼以下:

UserInfo
package json;

public class UserInfo {
public String username;
public String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}

result

代碼和運行結果都已經貼在每一個問題的後面,運行時直接用main方法分別對每一個方法運行便可看到測試效果。

note.txt是報的對應的錯誤及解決方法,也從另外一個方面說明爲何須要導入前面提到的jar包;

note.txt文件內容以下:

java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException 
at java.lang.ClassLoader.defineClass0(Native Method) 
at java.lang.ClassLoader.defineClass(ClassLoader.java:537) 
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123) 
at java.net.URLClassLoader.defineClass(URLClassLoader.java:251) 
at java.net.URLClassLoader.access$100(URLClassLoader.java:55) 
at java.net.URLClassLoader$1.run(URLClassLoader.java:194) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.net.URLClassLoader.findClass(URLClassLoader.java:187) 
at java.lang.ClassLoader.loadClass(ClassLoader.java:289) 
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274) 
at java.lang.ClassLoader.loadClass(ClassLoader.java:235) 
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302) 
at generate.TestJSONObject.main(TestJSONObject.java:40) 
Exception in thread "main" 
解決方案:導入commons-lang-2.1.jar

java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory 
at net.sf.json.JSONObject.<clinit>(JSONObject.java:125) 
at generate.TestJSONObject.main(TestJSONObject.java:40) 
Exception in thread "main" 
解決方案:導入commons-logging.jar

java.lang.NoClassDefFoundError: org/apache/commons/beanutils/DynaBean 
at net.sf.json.JSONObject.set(JSONObject.java:2164) 
at net.sf.json.JSONObject.put(JSONObject.java:1853) 
at net.sf.json.JSONObject.put(JSONObject.java:1806) 
at generate.TestJSONObject.main(TestJSONObject.java:41) 
Exception in thread "main" 
解決方案:導入commons-beanutils.jar

java.lang.NoClassDefFoundError: net/sf/ezmorph/MorpherRegistry 
at net.sf.json.util.JSONUtils.<clinit>(JSONUtils.java:65) 
at net.sf.json.JSONObject.set(JSONObject.java:2164) 
at net.sf.json.JSONObject.put(JSONObject.java:1853) 
at net.sf.json.JSONObject.put(JSONObject.java:1806) 
at generate.TestJSONObject.main(TestJSONObject.java:41) 
Exception in thread "main" 
解決方案:導入ezmorph-1.0.2.jar

java.lang.NoClassDefFoundError: org/apache/commons/collections/FastHashMap 
at org.apache.commons.beanutils.PropertyUtils.<clinit>(PropertyUtils.java:208) 
at net.sf.json.JSONObject.fromBean(JSONObject.java:190) 
at net.sf.json.JSONObject.fromObject(JSONObject.java:437) 
at net.sf.json.JSONObject.set(JSONObject.java:2196) 
at net.sf.json.JSONObject.put(JSONObject.java:1853) 
at net.sf.json.JSONObject.put(JSONObject.java:1806) 
at generate.TestJSONObject.main(TestJSONObject.java:41) 
Exception in thread "main" 
解決方案:導入commons-collections-3.0.jar

Exception in thread "main" java.lang.NoClassDefFoundError: nu/xom/Serializer 
at generate.TestJSONObject.jsonToXML(TestJSONObject.java:88) 
at generate.TestJSONObject.main(TestJSONObject.java:96) 
解決方案:導入xom-1.0d10.jar

 

幾點說明:

1.注意UserInfo類的修飾符,用public修飾,變量username和password也用public修飾,最好單獨的寫一個類,這裏就不貼出來了

2.以上json字符串和xml字符串都是最簡單的形式,實際開發中json字符串和xml格式比這個複雜的多,

處理複雜的json字符串,能夠封裝寫一個類繼承HashMap,而後重寫其put和get方法,以支持對類型爲A[0].B及A.B的鍵值的讀取和指定

3.以上6中狀況在實際開發中可能有些不存在或不經常使用

 

存在的問題:

1.使用XMLSerializer的write方法生成的xml字符串的中文亂碼問題

2.question4中的紅色的log日誌問題

2012-4-6 15:04:35 net.sf.json.xml.XMLSerializer getType 
信息: Using default type string

原文連接:http://www.cnblogs.com/javapan/archive/2012/04/07/JSONObject.html

示例:JSONObject對象使用

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 在線APIhttp://json-lib.sourceforge.net/apidocs/jdk15/index.html

相關文章
相關標籤/搜索