Ili*_*oly 7 json gson kotlin kotlin-exposed
我有以下用户表对象和实体类:
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
}
Run Code Online (Sandbox Code Playgroud)
有没有办法使用 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
}
}
Run Code Online (Sandbox Code Playgroud)
在这个人为的例子中并不是那么糟糕,但我想知道是否有更干燥的方法。
Exposed 不允许自己创建 DAO 对象,因为您总是需要将 an 传递EntityID给构造函数。但是,Jackson 支持读取现有对象。所以,你可以这样写:
transaction {
User.new {
mapper.readerForUpdating(this).readValue(json)
}
}
Run Code Online (Sandbox Code Playgroud)
为了确保 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
}
Run Code Online (Sandbox Code Playgroud)
另请注意,您不能@JsonProperty在委托属性上添加注释,但必须使用@get:JsonProperty.
为了使用 Jackson,请将以下内容添加到您的build.gradle文件中(如果您不使用 gradle,则必须使该代码适应您的构建系统):
compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.0"
Run Code Online (Sandbox Code Playgroud)
这是一个完整的示例:https : //gist.github.com/msrd0/1d8d3d76de4010cc72868d8a36f0560a
| 归档时间: |
|
| 查看次数: |
2234 次 |
| 最近记录: |