プログラミン初学者です。
タイトルの通りkotlinとJacksonを用いてLocalTimeなどのデータをシリアライズしたのですが
うまく実装できません。ご回答お願いします。
書いたコード
JacksonPractice.kt
@RestController
@RequestMapping("json")
class JacksonPractice {
@PostMapping(
value=[""],
consumes = ["application/json"]
)
fun postJsonData(@RequestBody json: String) {
println("called getJsonData")
println("----- json data -----")
println(json)
println("")
val mapper = ObjectMapper()
mapper.registerModule(JavaTimeModule())
val jsonData = mapper.readValue<JsonData>(json)
println("----- json serialize -----")
println(jsonData)
}
}
JsonDataModel.kt(データクラス)
package practice.kotlinjackson.model
import com.fasterxml.jackson.annotation.JsonFormat
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer
import java.time.LocalDateTime
import java.time.LocalTime
data class JsonData(
val id: Int,
val name: String,
@JsonSerialize(using = ToStringSerializer::class)
@JsonDeserialize(using = LocalDateTimeDeserializer::class)
val date : LocalDateTime,
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm:ss")
val time: LocalTime,
val jsonDataDetail: JsonDataDetail
)
data class JsonDataDetail(
val detail: String
)
guild.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.5.3"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
kotlin("jvm") version "1.5.21"
kotlin("plugin.spring") version "1.5.21"
}
group = "practice.kotlin-jackson"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.5")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
リクエストは下記のjsonデータをpostmanからリクエストしています
{
"id": 10,
"name": "kotlin jackson",
"date": "2017-11-13T06:40:00Z",
"time": "10:00:00",
"jsonDataDetail": {
"detail": "data detail"
}
}