Spring Boot REST API -使用Jackson反序列化带有方括号的查询属性

5ktev3wc  于 2022-11-09  发布在  Spring
关注(0)|答案(2)|浏览(149)

我正在调用一个遗留的rest端点。在那里我必须反序列化一个带有方括号 author[name] 的rest端点中的查询参数。

  • 问 *:是否可以将属性 author name 反序列化到AuthorDto(spring boot + kotlin)中?
import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.JsonProperty
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController

@RestController
class AuthorController {

    @GetMapping("/author/{id}")
    fun getAuthorFromLegacyApi(
        @PathVariable("id") id: Long,
        authorDto: AuthorDto?
    ) = ResponseEntity.ok(authorDto)

}

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
data class AuthorDto(
    @RequestParam(name = "author[name]")
    val name: String?,
    // long list of different query parameters
    val country: String? = null,
)
czq61nw1

czq61nw11#

是的,如果您使用@RequestParam("author[name]")注解authorDto,则这是可能的:

@GetMapping("/author/{id}")
fun getAuthorFromLegacyApi(@PathVariable("id") id: Long, @RequestParam("author[name]") authorDto: AuthorDto) = ResponseEntity.ok(authorDto.name)
nnt7mjpx

nnt7mjpx2#

用Map怎么样。

@GetMapping("/author/{id}")
    fun getAuthorFromLegacyApi(@PathVariable("id") id: Long, @RequestParam authorDto: Map<String, String>): String {
        return "Hello $id ${authorDto["author[name]"]} ${authorDto["currency"]}"
    }

我尝试使用author/5?author%5Bname%5D=Tom&currency=INR,得到了Hello 5 Tom INR的响应

相关问题