protected static void sendJsonObject ( RequestContext context , Object object , int statusCode ) throws IOException { final HttpServletResponse httpResponse = context . getResponse ( ) ; if ( httpResponse . isCommitted ( ) ) { log . fatal ( "Abort HTTP transaction. Attempt to send JSON object after reponse commited." ) ; return ; } log . trace ( "Send response object |%s|." , object . toString ( ) ) ; Json json = Classes . loadService ( Json . class ) ; String buffer = json . stringify ( object ) ; byte [ ] bytes = buffer . getBytes ( "UTF-8" ) ; httpResponse . setStatus ( statusCode ) ; httpResponse . setContentType ( ContentType . APPLICATION_JSON . getValue ( ) ) ; httpResponse . setContentLength ( bytes . length ) ; httpResponse . setHeader ( "Content-Language" , context . getLocale ( ) . toLanguageTag ( ) ) ; httpResponse . getOutputStream ( ) . write ( bytes ) ; httpResponse . getOutputStream ( ) . flush ( ) ; }
Send object back to client encoded JSON with given HTTP status code . Take care to set content type length and language . Content language is extracted from request context locale .