账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Kotlin JSON 序列化为空?
    52
    0

    Kotlin JSON 序列化为空?

    场景

    在尝试使用 Kotlin 结合 SpringBoot 开发后台的过程中,第一部就遇到了序列化的问题。使用https://start.spring.io/ 创建的项目,序列化的库是 Jackson,还需要特别的设置么?

    依赖项

    plugins {
        id 'org.springframework.boot' version '2.1.3.RELEASE'
        id 'org.jetbrains.kotlin.jvm' version '1.3.21'
        id 'org.jetbrains.kotlin.plugin.spring' version '1.3.21'
    }
    
    apply plugin: 'io.spring.dependency-management'
    
    group = 'com.*.*'
    version = '0.0.1-SNAPSHOT'
    sourceCompatibility = '1.8'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'org.springframework.boot:spring-boot-starter-aop'
        implementation 'org.springframework.boot:spring-boot-starter-web'
        implementation 'com.fasterxml.jackson.module:jackson-module-kotlin'
        implementation 'org.jetbrains.kotlin:kotlin-reflect'
        implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
        runtimeOnly 'mysql:mysql-connector-java'
        testImplementation 'org.springframework.boot:spring-boot-starter-test'
    }
    
    compileKotlin {
        kotlinOptions {
            freeCompilerArgs = ['-Xjsr305=strict']
            jvmTarget = '1.8'
        }
    }
    
    compileTestKotlin {
        kotlinOptions {
            freeCompilerArgs = ['-Xjsr305=strict']
            jvmTarget = '1.8'
        }
    }
    class Essay(private var id: Long?, private var content: String?, private var contentHtml: String?, private var createTime: LocalDateTime?, private var updateTime: LocalDateTime?) {
        override fun toString() = "Essay(id=$id, content=$content, contentHtml=$contentHtml, createTime=$createTime, updateTime=$updateTime)"
    }

    测试代码

    class EssayTest {
        private val log = LoggerFactory.getLogger(this::class.java)
        @Test
        fun test() {
            val essay = Essay(1, "content", "contentHTML", LocalDateTime.now(), LocalDateTime.now())
            log.info("essay: {}", essay)
            val om = ObjectMapper().registerModule(KotlinModule())
            log.info(om.writeValueAsString(essay))
        }
    }
    2
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    • 斑点熊猫 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部