Search code examples
spring-bootkotlinjpa

POST payload is zero in Spring Boot Service


I have a problem with my payload which I send from a ReactJS application to a SpringBoot service. As you can see in the first picture, the payload is filled. However, if I set a debugger in the backend, both fields are empty or zero. Why is this so? What am I doing wrong?

React frontend:

const saveOffer = async (offers: Offer[], newUser: User) => {
var objects = {
  offers,
  newUser,
};
const res = await axios.post(
  'http://...'/api/offer',
  { objects }
 );
};

Offer.tk

 @RestController
 @RequestMapping("/api/offer")
 class OfferController {

 @PostMapping
 fun saveOffer(@RequestBody objects: ObjHolder): Boolean {
    var simpleUser = objects.newUser
    var offers = objects.offers

     return true
  }
 }

ObjHolder.tk:

 data class ObjHolder(
  var offers: List<Offer>? = mutableListOf(),
  var newUser:User?
)

Payload:

enter image description here

Debugger: enter image description here


Solution

  • Looks all ok, here are some things to try:

    1. Are you configuring Jackson in any way as your serialization helper in Spring? Perhaps it is not configured to deserialize to Kotlin. Once this is configured in something like the following way you can use data class with val constructors without any special configuration:
    @Configuration
    class ObjectMapperConfig {
    
        @Bean
        fun makeObjectMapper(): ObjectMapper {
            return JsonMapper.builder()
                .addModule(KotlinModule.Builder().configure(KotlinFeature.StrictNullChecks, true).build())
                .addModule(JavaTimeModule())
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .build()
        }
    }
    
    1. Temporarily change the saveOffer parameter to be a String and see what you get:
        fun saveOffer(@RequestBody map: Map<String, Any>): Boolean {
            println(map)
        }
    
    1. Change @PostMapping annotation to @PostMapping(consumes = [MediaType.APPLICATION_JSON_VALUE]) but I think that's the default.

    2. On the client send a header like Content-Type: application/json; charset=utf-8