当值包含引号时,在Spring Controller中正确解析JSON

问题描述 投票:3回答:1

我需要在Spring Web服务中接收和解析一些JSON。 JSON在HTTP POST请求中发送,我无法控制此请求的格式,标题等。这是请求的示例:

{
"u": 1,
"t": "token",
"rental": "rental_name",
"address": "rental_address",
"arrive": "Monday, Jan. 1 2018",
"depart": "Wednesday, Jan. 3 2018",
"adults": 1,
"children": 0,
"guest": "guest_name",
"keys": "key location with "quotes" goes here",
"inquiry": "inquiry_id"
}

请注意,“keys”的值中包含双引号。

当我在Spring控制器中使用请求时,我可以理解得到以下异常,因为该值中的引号令人困惑:

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

这是我的Spring Controller接收POST请求的方法:

@RequestMapping(value ="/booking_new", method = RequestMethod.POST, consumes = MediaType.ALL_VALUE)
public ResponseEntity newBooking(@RequestBody Booking payload){
    //Extract values from the generated Booking object etc
}

我无法接收@RequestBody作为字符串,只是转义引号,因为所有引号都将被转义,使JSON无效。

有什么办法可以在请求进来时以某种方式逃脱或删除任何值中的引号?

java json spring jackson gson
1个回答
0
投票

虽然我无法控制包含JSON值的变量,但我发现我确实可以控制整个POST请求的格式。

所以我最终格式化为XML而不是JSON,因为它更容易解决双引号问题。

© www.soinside.com 2019 - 2024. All rights reserved.