Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between 'APPLICATION_JSON' and 'APPLICATION_JSON_VALUE'

Tags:

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( ... ) { ... } 
like image 568
PrabaharanKathiresan Avatar asked Jul 27 '16 13:07

PrabaharanKathiresan


People also ask

What is the use of MediaType Application_json_value?

The produces = MediaType. APPLICATION_JSON_VALUE means that the response that will be produced will be converted into JSON format.

Why is APPLICATION_JSON_UTF8_VALUE deprecated?

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 .

What is Java MediaType?

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)

What is the default media type in spring boot?

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.


1 Answers

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.

like image 112
Andy Wilkinson Avatar answered Oct 11 '22 11:10

Andy Wilkinson