日期:2014-05-16 浏览次数:20440 次
在用JSONObject.fromObject的时候,如果JavaBean中有Set等类型时,会报错hibernate的lazy的错,所以需要过虑掉那些无关的类型。直接贴代码:
public class MagazineModel {
private int id;
private String name;
private int score;
private String descript;
private Set<PaperModel> papers;
private Set<MagazineModel> magazines;
private MagazineModel magazine;
get() set().....
}
要过滤掉papers magazines magazine
public static String modelBeanToJSON(final List<String> filterField, List<?> list){
JSONArray jsonObjects = new JSONArray();
int i=0;
Iterator<?> it = list.iterator();
while(it.hasNext()){
JSONObject jsonObject = new JSONObject();
Object obj = it.next();//这里的Obj对象只是list中的存放的对象类型
JsonConfig jsonConfig = new JsonConfig();
PropertyFilter filter = new PropertyFilter() {
public boolean apply(Object source, String name, Object value) {
boolean isFiltered=false;
for(String string:filterField){
if(string.equals(name)){
isFiltered=true;
}
}
if (isFiltered) {
return true;
}
return false;
}
};
jsonConfig.setJsonPropertyFilter(filter);
jsonObject=JSONObject.fromObject(obj, jsonConfig);
jsonObjects.add(i++, jsonObject);
}
return jsonObjects.toString();
}
调用示例:
List<MagazineModel> magas=paperService.findParentMagzines();//用hibernate 得到MagazineModel
List<String> strings=new ArrayList<>(); &nbs