dropwizard: produce both html and json from the same class

泄露秘密 提交于 2019-12-23 01:17:12

问题


Is there a way to control the output format from the client side?

I have a class which

@Produces(MediaType.TEXT_HTML)

and I want it to produce json when the client requests.

I can copy the class verbatim, replacing only the @Path and @Produces annotations, but this looks like a total waste.

I wonder if the client could append something like &content-type=application/json to the URL and have my server respond with json instead of html?


回答1:


You'll need to annotate the resources as providing both HTML and JSON:

@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})

Then just make sure you have MessageBodyWriter implementations registered to handle the method's return type. Dropwizard's JacksonMessageBodyProvider should handle the JSON; if you're using Dropwizard Views, ViewMessageBodyWriter should handle the rest. Jersey will do the content negotiation with the client, provided your client has application/json in the request's Accept header.



来源:https://stackoverflow.com/questions/11637365/dropwizard-produce-both-html-and-json-from-the-same-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!