以下是一個通用的對象轉json的方法,使用的fastjson的SimplePropertyPreFilter 對象,個人感覺比使用PropertyPreFilter的匿名內部類形式的過濾器更好用!
/**
* 將對象序列化爲json
*/
public void objectToJson(Object obj, String[] args) {
//屬性過濾器對象
SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
//屬性排斥集合,強調某些屬性不需要或者一定不能被序列化
Set<String> excludes = filter.getExcludes();
//屬性包含集合,強調僅需要序列化某些屬性.具體用哪一個,看實際情況.此處我用的前者
//Set<String> includes = filter.getIncludes();
//排除不需序列化的屬性
for (String string : args) {
excludes.add(string);
}
//調用fastJson的方法,對象轉json,
//參數一:需要被序列化的對象
//參數二:用於過濾屬性的過濾器
//參數三:關閉循環引用,若不加這個,頁面無法展示重複的屬性值
String string = JSON.toJSONString(obj, filter,SerializerFeature.DisableCircularReferenceDetect);
}
頁面中js判斷json對象是否包含某個key
JSON.hasOwnProperty(“propertyName”)
包含返回true,反之返回false
JQuery 遍歷json
$.each(jsonData, function (index, value) {
.....
.....
.....
});
js中字符串轉json
JSON.parse(string)
js中json轉字符串
JSON.stringify(jsonData)
js中刪除json對象中的一個key
var jsonObj={“type”:“information”,“result”:“success”,“item”:null};
delete jsonObj.item;