So I realized I am not actually getting JSON in th...
# spring
p
So I realized I am not actually getting JSON in the
@PostMapping
so it won't use Jackson at all. Can Spring bind form data to Kotlin data class?
m
Copy code
@PostMapping(value = ["/upload"], produces = arrayOf("application/json;charset=UTF-8"))
    @ResponseBody
    fun uploadStlFile(
            @RequestParam(required = true) file: MultipartFile
    )
p
your endpoint consumes files, mine:
Copy code
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE
m
I think you will be able to handle form data with spring 😃 if its possible to handle files with miltipart
p
I don't think so.. In this example it works when
PersonDTO
is a java class but not when it is a Kotlin data class
Copy code
@PostMapping(value = "/submit", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String submit(PersonDTO data)
t
that might be because of reflection
Kotlin data classes must have all fields populated once construction is done
but if you provide default values to your fields and make those fields
var
, you might make some headway
I’m imagining that Spring is trying to create an instance of your DTO, and then call the appropriate setters on the fields it has found
so I’m imagining your PersonDTO might look like:
Copy code
data class PersonDTO (
    val firstName: String,
    val lastName: String,
    val email: String
)
but what you might need is something like:
Copy code
data class PersonDTO (
    var firstName: String = "",
    var lastName: String = "",
    var email: String = ""
)
this way, PersonDTO has a default constructor, and you can set the field values post-construction
I could be completely wrong though
p
I think you are exactly right except one there is one problem: I don't like mutable Kotlin data classes. 😄
t
I think you can make a workaround for that with kotlin-reflect and everything
I know I did something similar for data classes and Spring Data
lemme check something real quick
so yeah - I use this so that I can instantiate
@Entity
data classes with a no-arg constructor
but still keep my immutability
what you could do is create a marker interface like
interface DTO
and then have
@DTO data class PersonDTO
seems like an extra step and feels very much like Guice
but that’s not to say it’s a bad practice or anything