java 如何将字符串@RequestBody 自动解析为json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34001725/
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
How to automatically parse String @RequestBody as json
提问by riddy
I have an endpoint which should read a string value as body.
我有一个端点,它应该读取一个字符串值作为正文。
@RestController
public class EndpointsController {
@RequestMapping( method = RequestMethod.PUT, value = "api/{myId}/name", consumes= MediaType.APPLICATION_JSON )
public String updateName( @PathVariable( MY_ID ) String myId, @RequestBody String name) {
//will be: "new name"
//instead of : newname
return myId;
}
}
My problem is, that client will call this with "new name" which is correct IMHO but the server reads this with the quotes, because it does not handle the string as a json object. How can I tell Hymanson to parse the string as well (same way than it does with Pojos)?
我的问题是,该客户端将使用“新名称”调用它,恕我直言,这是正确的,但服务器用引号读取它,因为它不会将字符串作为 json 对象处理。我怎样才能告诉 Hymanson 解析字符串(与 Pojos 的解析方式相同)?
回答by Sotirios Delimanolis
If you're using Hymanson as your JSON parser, you can simply declare your parameter with the type TextNode
. This is the Hymanson type representing JSON strings.
如果您使用 Hymanson 作为 JSON 解析器,则只需使用类型声明参数即可TextNode
。这是表示 JSON 字符串的 Hymanson 类型。
public String updateName(@PathVariable(MY_ID) String myId, @RequestBody TextNode name) {
You can then use its asText
method to retrieve its text value.
然后您可以使用它的asText
方法来检索其文本值。