Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Lazy JSON Serialization
@Component
public class LazyJSONSerialization extends XStreamJSONSerialization {
private SerializerHolder holder;
public LazyJSONSerialization(SerializerHolder holder, HttpServletResponse response, TypeNameExtractor extractor, ProxyInitializer initializer, XStreamBuilder builder) {
super(response, extractor, initializer, builder);
this.holder = holder;
}
@Override
protected SerializerBuilder getSerializer() {
try {
return new XStreamSerializer(getXStream(), holder.createWriter(), extractor, initializer);
} catch (IOException e) {
throw new ResultException("Unable to serialize data", e);
}
}
}
@Intercepts(before=HibernateTransactionInterceptor.class)
public class LazySerializerInterceptor implements Interceptor {
public LazySerializerInterceptor(SerializerHolder holder, HttpServletResponse response) {
this.holder = holder;
this.response = response;
}
public boolean accepts(ResourceMethod method) { return true; }
public void intercept(InterceptorStack stack, ResourceMethod method, Object instance) {
stack.next(method, instance);
if (holder.getWriter() != null) {
response.getWriter().print(holder.getWriter());
}
}
}
@Component
public class SerializerHolder {
private StringWriter writer;
public Writer createWriter() {
this.writer = new StringWriter();
return this.writer;
}
public Writer getWriter() {
return this.writer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.