FastJson過濾屬性、判斷json是否存在某個key、刪除json中的一個key

以下是一個通用的對象轉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;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章