gson Kotlin-解析json字符串时抛出MalformedJsonException:未终止的对象

h5qlskok  于 2022-11-06  发布在  Kotlin
关注(0)|答案(1)|浏览(311)

我正在尝试将值保存到jsonb DB列:

val deliveryAddressAsJson = deliveryAddress?.toJson()
  val lat = deliveryAddressAsJson?.get("latitude")
  val lng = deliveryAddressAsJson?.get("longitude")
  val dataJson = jsonObject("comment" to "KARTKOORD:#LE#$lat#$lng# #")
  val values = mapOf(
      "type" to EventType.RESOLVED.dbName,
      "created_by" to ctx.userId,
      "data" to dataJson.toPgObject(),
      "package_id" to packageId
  )

  @Language("PostgreSQL")
  val sql = """insert into package_event(type, created_by, data, package_id) values (:type, :created_by, :data, :package_id)""".trimMargin()

  insert(ctx, sql, values).bind()

我可以看到数据是这样保存的:

data -> {Collections$SingletonMap@6348}  size = 1
  key = "data"
  value = {Collections$SingletonMap@6348}  size = 1
     key = "comment"
     value = "KARTKOORD:#LE#59.8098962#10.7809297# #"

但是,如果我试着解析它:

val resolvedPackageEvent = fetchRows(ctx, queryOf("select * from package_event where package_id = ? and type = 'resolved'", packageId)).first()

  val data = parseJson(resolvedPackageEvent.string("data"))
  val deliveryAddress = data.get("comment")

我得到一个抛出的异常:

com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 20 path $.comment

如果我尝试使用jsonObject方法获取值,如下所示:

fun Entity.jsonObject(key: String): JsonObject = when (val v = this[key]) {
  is String -> parseJson(v)
  else -> v as JsonObject
}

resolvedPackageEvent.jsonObject("data")

我得到一个异常:

java.lang.ClassCastException: class java.util.Collections$SingletonMap cannot be cast to class com.google.gson.JsonObject (java.util.Collections$SingletonMap is in module java.base of loader 'bootstrap'; com.google.gson.JsonObject is in unnamed module of loader 'app')

我应该如何解析这个json字符串?

4urapxun

4urapxun1#

您的数据不是字符串。

{
  "data": {
    "comment": "KARTKOORD:#LE#59.8098962#10.7809297# #"
  }
}

我手头没有gson语法,因此无法提供用于检索值的精确代码。

val result: JsonObject = parseJson(resolvedConsignmentEvent)
val data: JsonObject = result.get("data")
val deliveryAddress: String = data.get("comment")

相关问题