1. 程式人生 > >一些json資料格式轉換的例子

一些json資料格式轉換的例子

question1:後臺接受到前臺的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);
}

question2:後臺是怎麼拼裝json格式的字串?

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());
}


question3: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);
}


question4: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());
}

question5: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());
}


question6: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;
}

}

第三種方式是使用ContentNegotiatingViewResolver來設定輸出為json格式,需要修改servlet context配置檔案如下

<bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="1" />
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean
                    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
            </list>
        </property>
        <property name="ignoreAcceptHeader" value="true" />
    </bean>
但這種格式的輸出會返回{model類名:{內容}} 的json格式, 例如,以下程式碼
@RequestMapping("/json3.json")
    public JsonResult testJson3(@RequestBody User u){
        log.info("handle json output from ContentNegotiatingViewResolver");
        return new JsonResult(true,"return ok");
    }
期望的返回是 {success:true,message:”return ok”}; 但實際返回的卻是 {"jsonResult":{"success":true,"msg":"return ok"}} 原因是MappingJacksonJsonView中對返回值的處理未考慮modelMap中只有一個值的情況,直接是按照mapName:{mapResult}的格式來返回資料的。 修改方法,過載MappingJacksonJsonView類並重寫filterModel方法如下
protected Object filterModel(Map<String, Object> model) {  
        Map<?, ?> result = (Map<?, ?>) super.filterModel(model);  
        if (result.size() == 1) {  
            return result.values().iterator().next();  
        } else {  
            return result;  
        }  
    }
對應的ContentNegotiatingViewResolver修改如下
<bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="1" />
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean
                    class="net.zhepu.json.MappingJacksonJsonView" />
            </list>
        </property>
        <property name="ignoreAcceptHeader" value="true" />
    </bean>

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