暴露:如何将JSON解析为Entity类

问题描述 投票:2回答:1

我有以下用户表对象和实体类:

object UserTable : IntIdTable() {
    val name = varchar("name", 256)
}

class User(id: EntityID<Int>): IntEntity(id) {
    companion object : IntEntityClass<User>(UserTable)
    val name by UserTable.name
}

有没有办法使用Gson(或其他一些库)将JSON解析为User实例,然后插入它?据我所知,似乎我必须创建一个中间UserData数据类,然后手动复制字段。

data class UserData {
  var id: Int?
  var name: String?
}

fun main() {
  val data = Gson().fromJson<UserData>("...", UserData::class.java)
  val user = User.new {
    name = data.name
  }
}

在这个人为的例子中并没有那么糟糕,但我想知道是否有一种干涸的方法。

json kotlin gson kotlin-exposed
1个回答
2
投票

暴露不允许自己创建DAO对象,因为您总是需要将EntityID传递给构造函数。但是,Jackson supports reading an existing object。所以,你可以这样写:

transaction {
    User.new {
        mapper.readerForUpdating(this).readValue(json)
    }
}

为了确保Jackson和Exposed不会干扰,你必须像这样创建你的mapper

val mapper by lazy {
    val mapper = jacksonObjectMapper()
    mapper.setAnnotationIntrospector(object : JacksonAnnotationIntrospector() {
        override fun hasIgnoreMarker(m : AnnotatedMember)
            =  (m.getDeclaringClass() == IntEntity::class.java)
            || (m.getDeclaringClass() == Entity::class.java)
            || super.hasIgnoreMarker(m)
    })
    mapper
}

另请注意,您不能将@JsonProperty注释放在委托属性上,但必须使用@get:JsonProperty

要使用Jackson,请将以下内容添加到build.gradle文件中(如果您不使用gradle,则必须将该代码调整到您的构建系统):

compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.0"

这是一个完整的例子:https://gist.github.com/msrd0/1d8d3d76de4010cc72868d8a36f0560a

© www.soinside.com 2019 - 2024. All rights reserved.