【问题标题】:Exposed: How to parse JSON into an Entity class暴露:如何将 JSON 解析为实体类
【发布时间】:2018-06-17 21:41:32
【问题描述】:

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

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】:

    Exposed 不允许自己创建 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

    【讨论】:

    猜你喜欢
    • 2012-01-03
    • 2016-11-01
    • 2023-03-31
    • 2015-08-08
    • 2017-04-04
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多