I'll post here my question. :slightly_smiling_face...
# getting-started
a
I'll post here my question. 🙂 I'm very new to Java/Kotlin - I've mostly been a php dev throughout my carrier, so just learning here. First question: How do I control JSON serialization when sending a POST to a controller action?
Copy code
@PostMapping("/")
fun addAnnouncement(@RequestBody dto: AnnouncementDTO) {
    println(dto);
    manager.addAnnouncement(dto.toAnnouncement())
}
This is my body:
Copy code
{
  "text": "Hello",
  "occupant": "35A",
  "date": "2020-10-09"
}
It works. Second question: Why? I'm assuming this might not be even a kotlin-specific question, rather Spring, but as I said, I'm quite new at this so excuse some confusion. 🙂
t
the easiest answer (not because I am jerk) is read the docs. I assume you are using Spring boot, there is a lot of stuff that is done by “magic” in Spring Boot (which is sort of the point, removing mundane work from the developer). if you care about understanding the nitty gritty details (which you should, otherwise good luck when things go wrong) docs and blogs online are your best resource
a
Honestly, I tried Googling the docs and can't say I had much luck with that. But I think I've found my answer.
t
this being said, Spring MVC starter comes preconfiguring Jackson, which is one of the main libraries to convert from json to java/kotlin classes
yeah, docs are not easy at the beginning, at least they are not for me. after awhile it gets easier, but it is an investment
small doses at a time, only suggestion I can give 🙂
a
There's a class
RequestResponseBodyMethodProcessor
which processes all the requests. In in there's a method called
readWithMessageConverters
which calls it's parent (from the abstract class) that contains a bunch of converters (
this.messageConverters
) - an array of various converters that have a
canRead
method. At some point
AbstractJackson2HttpMessageConverter
is invoked and
canDeserialize
method is checked. After that a converter is invoked and Jackson takes over and converts it to the class.
It's similar to what Symfony (php framework, heavily influenced by Spring) does internally, so it seems familiar. I kind of assumed so, just didn't have the confirmation. 🙂