RequestBody解析为json

RequestBody解析为json

本文介绍了如何自动将String @RequestBody解析为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个端点,应该将字符串值作为正文读取。

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;
   }
}

我的问题是,该客户将使用新名称这是正确的恕我直言,但服务器用引号读取此,因为它不会将字符串作为json对象处理。我怎么能告诉杰克逊解析字符串(与Pojos相同)?

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 Jackson to parse the string as well (same way than it does with Pojos)?

推荐答案

如果您使用Jackson作为JSON解析器,则只需使用。这是代表JSON字符串的Jackson类型。

If you're using Jackson as your JSON parser, you can simply declare your parameter with the type TextNode. This is the Jackson type representing JSON strings.

public String updateName(@PathVariable(MY_ID) String myId, @RequestBody TextNode name) {

然后你可以使用它的 asText 检索其文本值的方法。

You can then use its asText method to retrieve its text value.

这篇关于如何自动将String @RequestBody解析为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 05:47