问题
Using jersey jersey.java.net How do I set JSON as the default serialization instead of XML when there is no accept header or .xml suffix is in the URI?
回答1:
You can assign the quality index to each media type in @Produces annotation. I.e.you can do the following to make Jersey prefer JSON if both XML and JSON are allowed:
@Produces({"application/json;qs=1", "application/xml;qs=.5"})
回答2:
You should be able to set the @Produces annotation to specify the return format like so:
@Produces( { "application/json" })
How come there is no accepts header?
回答3:
You can specify preference of generation by specifying media types in your order of preference in the @Produces annotation.
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
In the above code since "application/json" comes first, if no accept header is specified in the request Jersey will default to generating JSON response.
Using qs (as suggested by Martin) makes the preference more explicit, but its a bit more complicated to understand.
来源:https://stackoverflow.com/questions/7649259/how-to-set-to-default-to-json-instead-of-xml-in-jersey