I am new to spring development and want to know what is the difference between MediaType.APPLICATION_JSON_VALUE
and MediaType.APPLICATION_JSON
?
I have a thought of both are representing same application/json
content type but if I put MediaType.APPLICATION_JSON
some compiler errors are shown to add @controller
and @ResponseBody
annotations to my rest controller and When to use MediaType.APPLICATION_JSON
?
@RequestMapping(value="/invite", method = POST, consumes = { MediaType.APPLICATION_JSON }) public @ResponseBody String sendInvite( ... ) { ... }
The produces = MediaType. APPLICATION_JSON_VALUE means that the response that will be produced will be converted into JSON format.
APPLICATION_JSON_UTF8_VALUE. Deprecated. as of 5.2 in favor of APPLICATION_JSON_VALUE since major browsers like Chrome now comply with the specification and interpret correctly UTF-8 special characters without requiring a charset=UTF-8 parameter. A String equivalent of APPLICATION_JSON_UTF8 .
MediaType(String type, String subtype) Creates a new instance of MediaType with the supplied type and subtype. MediaType(String type, String subtype, Map<String,String> parameters) Creates a new instance of MediaType with the supplied type, subtype and parameters. MediaType(String type, String subtype, String charset)
In Spring REST APIs, Spring uses 'application/json' as a default media type. That is why, a REST controller can consume or produce JSON format payloads without having to specify the media types explicitly. Thus, in order to consume or produce data in a different form, the controller needs to specify that explicitly.
To quote the javadoc, MediaType.APPLICATION_JSON
is a "public constant media type for application/json
", whereas MediaType.APPLICATION_JSON_VALUE
is a "String equivalent of MediaType.APPLICATION_JSON
".
Attributes on Java annotations can only be one of a limited set of types. This prevents MediaType
from being used as an annotation attribute. To overcome this, a String
is used instead along with the various String
constants on MediaType
including MediaType.APPLICATION_JSON_VALUE
.
Outside of an annotation, if you want to refer to a media type you should use the more strongly typed MediaType
rather than passing around a String
that may or may not actually be a media type. So, for example, you'd use MediaType.APPLICATION_JSON
rather than MediaType.APPLICATION_JSON_VALUE
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With