Created
July 13, 2013 17:11
-
-
Save lucascs/5991378 to your computer and use it in GitHub Desktop.
Lazy JSON Serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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()); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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