Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

spring - Parse resquest Payload to Object

I'm new to Kotlin/ Java World. So I need a little help to parse an old fashion request in an easy way.

My controller was working perfectly before the new Request.


fun create(
    @RequestBody @NotEmpty request: PersonRequest,
) = service.create(mapper.toDto(request)) 

New BodyRequest:

    "fields": [
            "id": "name",
            "value": "blablabla"
            "id": "phone",
            "value": "+1 11111111"
            "id": "birthday",
            "value": "2000-01-01"

My Class:

class PersonRequest(

        var name: String?,

        @field: Pattern(regexp = "blabla") 
        var phone: String?,

        var birthday: LocalDate?

Any tips? Thanks!

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The request body you posted doesn't match the class PersonRequest.

Change the request body structure to:

  "name": "blablabla",
  "phone": "+1 11111111",
  "birthday": "2000-01-01"


Since you can't update the request structure, your other option is to change the class structure by creating two classes as below:

class PersonRequest(var fields: List<Field>)

class Field(var id: String, var value:Any)


The last step, which is optional based on your requirement, is that you can manipulate the PersonRequest class now and convert it to any other class using normal setters/getters.


To convert the List<Field> to PersonRequest, you could do it like this:

val personRequest = PersonRequest()
fields.forEach {
  when(it.id) {
    "name" -> personRequest.name = it.value
    "phone" -> personRequest.phone = it.value
    "birthday" -> personRequest.birthday = it.value

Not the neatest of codes, but...

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share