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

Categories

0 votes
1.1k views
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.

MyController:

@PostMapping("/create")
@ResponseStatus(OK)
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"
}

UPDATE:

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)

UPDATE 2:

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.

UPDATE 3:

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
...