FastJson过滤属性、判断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);

}

页面判断json对象是否包含某个key
JSON.hasOwnProperty(“propertyName”)
包含返回true,反之返回false

JQuery 遍历json

$.each(jsonData, function (index, value) {
    .....
    .....
    .....
});

字符串转json
JSON.parse(string)
json转字符串
JSON.stringify(jsonData)

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