JsonConfig的jsonConfig.setExcludes的用法
之前写一个小东西,当用JSONArray.fromObject()方法转一个对象集合时,因为对象中存在一对多的关系,一直抛出异常
严重: Error executing FreeMarker template
FreeMarker template error:
Java method “org.apache.commons.lang.exception.NestableRuntimeException.getMessage(int)” threw an exception when invoked on net.sf.json.JSONException object “net.sf.json.JSONException: org.hibernate.LazyInitializationException: Failed to lazily initialize a collection of role: cn.zzuli.app.domain.User.positions,no session or session was closed”; see cause exception in the Java stack trace.
FTL stack trace (“~” means nesting-related):
- Failed at: ${msg[0]?html} [in template “org/apache/struts2/dispatcher/error.ftl” at line 68,column 29]
Java stack trace (for programmers):
freemarker.core._TemplateModelException: [… Exception message was already printed; see it above …]
at freemarker.ext.beans._MethodUtil.newInvocationTemplateModelException(_MethodUtil.java:311)
at freemarker.ext.beans._MethodUtil.newInvocationTemplateModelException(_MethodUtil.java:275)
at freemarker.ext.beans.SimpleMethodModel.exec(SimpleMethodModel.java:80)
at freemarker.ext.beans.SimpleMethodModel.get(SimpleMethodModel.java:86)
at freemarker.core.DynamicKeyName.dealWithNumericalKey(DynamicKeyName.java:104)
at freemarker.core.DynamicKeyName._eval(DynamicKeyName.java:69)
at freemarker.core.Expression.eval(Expression.java:78)
at freemarker.core.Expression.evalAndCoerceToString(Expression.java:82)
at freemarker.core.BuiltInForString._eval(BuiltInForString.java:26)
at freemarker.core.Expression.eval(Expression.java:78)
at freemarker.core.Expression.evalAndCoerceToString(Expression.java:82)
at freemarker.core.DollarVariable.accept(DollarVariable.java:40)
at freemarker.core.Environment.visit(Environment.java:312)
at freemarker.core.MixedContent.accept(MixedContent.java:62)
at freemarker.core.Environment.visitByHiddingParent(Environment.java:333)
at freemarker.core.IfBlock.accept(IfBlock.java:48)
at freemarker.core.Environment.visitByHiddingParent(Environment.java:333)
at freemarker.core.IteratorBlock
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.NullPointerException
at freemarker.ext.beans.SimpleMethod.unwrapArguments(SimpleMethod.java:53)
at freemarker.ext.beans.SimpleMethodModel.exec(SimpleMethodModel.java:72)
… 44 more
然后通过询问别人,知道了JsonConfig的jsonConfig.setExcludes()这个方法,简单的说,这个就是过滤掉不需要的属性,因此就可以用这个方法过滤掉对象中存在的一对多的关系
List userList = userService.findAll();
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[]{“area”});
JSON json = JSONSerializer.toJSON(userList,jsonConfig);
setExcludes()里面的集合,就是你想要过滤掉的属性的名字。