java “APPLICATION_JSON”和“APPLICATION_JSON_VALUE”之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38614050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:35:39  来源:igfitidea点击:

difference between 'APPLICATION_JSON' and 'APPLICATION_JSON_VALUE'

javaspringspring-mvc

提问by PrabaharanKathiresan

I am new to spring development and want to know what is the difference between MediaType.APPLICATION_JSON_VALUEand MediaType.APPLICATION_JSON?

我是 Spring 开发的新手,想知道MediaType.APPLICATION_JSON_VALUE和之间有什么区别 MediaType.APPLICATION_JSON

I have a thought of both are representing same application/jsoncontent type but if I put MediaType.APPLICATION_JSONsome compiler errors are shown to add @controllerand @ResponseBodyannotations to my rest controller and When to use MediaType.APPLICATION_JSON?

我认为两者都表示相同的application/json内容类型,但是如果我将MediaType.APPLICATION_JSON一些编译器错误显示为向我的其余控制器添加@controller@ResponseBody注释以及何时使用MediaType.APPLICATION_JSON

@RequestMapping(value="/invite", method = POST, consumes = { MediaType.APPLICATION_JSON })
public @ResponseBody String sendInvite( ... ) { ... }

回答by Andy Wilkinson

To quote the javadoc, MediaType.APPLICATION_JSONis a "public constant media type for application/json", whereas MediaType.APPLICATION_JSON_VALUEis a "String equivalent of MediaType.APPLICATION_JSON".

引用javadocMediaType.APPLICATION_JSON是“公共常量媒体类型application/json”,而是MediaType.APPLICATION_JSON_VALUE“字符串等价物MediaType.APPLICATION_JSON”。

Attributes on Java annotations can only be one of a limited set of types. This prevents MediaTypefrom being used as an annotation attribute. To overcome this, a Stringis used instead along with the various Stringconstants on MediaTypeincluding MediaType.APPLICATION_JSON_VALUE.

Java 注释上的属性只能是一组有限的类型之一。这可以防止MediaType被用作注释属性。为了克服这个问题, aString与包括的各种String常量一起使用。MediaTypeMediaType.APPLICATION_JSON_VALUE

Outside of an annotation, if you want to refer to a media type you should use the more strongly typed MediaTyperather than passing around a Stringthat may or may not actually be a media type. So, for example, you'd use MediaType.APPLICATION_JSONrather than MediaType.APPLICATION_JSON_VALUE.

在注解之外,如果你想引用一个媒体类型,你应该使用更强类型的MediaType而不是传递一个String实际上可能是也可能不是媒体类型的 a 。因此,例如,您将使用MediaType.APPLICATION_JSON而不是MediaType.APPLICATION_JSON_VALUE.