Atitit.json類庫的設計與實現 ati json lib html
1. 目前jsonlib庫可能有問題,可能版本衝突,拋出ex1java
2. 解決之道:1json
2.1. 自定義json解析庫,使用多個複合的json 解析複合的引擎1ui
3. 幾個要點2this
3.1. 複合結構的轉換2google
3.2. 沒有get set方法的屬性自動忽略,而不拋出異常2spa
3.4. Api使用json lib的,以及gson的也一個2code
4. 普通的的json解析器 Jackson類庫 Google Gson JSON-lib類庫3
5.1. toJson xxx.fromObject(x).toString(2)3
5.2. 字符串轉成對象 T fromJson(String str, Class<T> type) fromObject(object)3
做者:: 老哇的爪子 Attilax 艾龍, EMAIL:1466519819@qq.com
轉載請註明來源: http://www.cnblogs.com/attilax/
一、如,一個Map是這樣的,Map<String, Map<String, List<String>>> map,若是這樣使用gson.toJson(map)得不到正確的結果的話,那麼,咱們可能要這樣使用,gson.toJson(map,new TypeToken<Map<String, Map<String, List<String>>>>(){}.getType())。
解決方案:
1、若是涉及到關聯屬性的對象,轉換前能夠先把它的關聯屬性轉換並放入一個新建的Map或者List,而後按照層次結構重複這樣的操做一層一層的往上轉,這樣,通常能夠解決問題,可是,若是關聯的層次比較深,作起來就很麻煩了。上面提到的問題3就能夠用這種方式解決。
package com.attilax.json;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.attilax.core;
import com.google.gson.Gson;
public class JSONObject {
public JSONObject(Map m) {
this.obj = m;
}
public static void main(String[] args) {
Map m = new HashMap();
m.put("d", new Date());
// m.put(key, value)
JSONObject.fromObject(m).toString(2);
}
private String toString(int i) {
// if(i==2) //fmt
{
try {
return net.sf.json.JSONObject.fromObject(this.obj).toString(i);
} catch (Exception e) {
try {
// 建立一個gson對象
Gson gson = new Gson();
// 轉換成json
String json = gson.toJson(this.obj);
return json;
} catch (Exception e2) {
return JsonUtil4jackjson.buildNormalBinder().toJson(
this.obj);
}
}
}
}
public Object obj;
private static JSONObject fromObject(Map m) {
// TODO Auto-generated method stub
return new JSONObject(m);
}
}