Gson-如何在Kotlin中解析部分json

时间:2019-06-26 11:29:40

标签: android json parsing kotlin gson

我有一个叫data class的{​​{1}},

Model

我有两个data class Model(var name: String? = null, var address: String? = null) { override fun toString(): String { return "name: $name address: $address" } } 字符串,

json

下面的转换工作正常,

val json1 = "{ \"name\": \"Alex\", \"address\": \"rome, 1000\" }"
val json2 = "{ \"name\": \"Alex\", \"address\": {\"city\": \"rome\", \"post\": \"1000\" } }"

但是,此版本不起作用。给出例外。

val model1 = Gson().fromJson<Model>(json1, Model::class.java)

异常:

val model2 = Gson().fromJson<Model>(json2, Model::class.java)

我如何解析E/AndroidRuntime: FATAL EXCEPTION: main Process: com.achellies.kotlin, PID: 11211 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.achellies.kotlin/com.achellies.kotlin.MainActivity}: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 40 path $.address at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3086) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3229) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:214) at 以便json2字段将保存内部地址json数据的字符串值?例如,解析address后应等于

address

4 个答案:

答案 0 :(得分:1)

您尝试使用Any吗?

data class Model(var name: String? = null, var address: Any? = null) {

    override fun toString(): String {
        return "name: $name address: $address"
    }
}

尝试一下,它将起作用。

祝你有美好的一天。 :)

答案 1 :(得分:1)

您可以使用专门用于JsonDeserializer类的Model,如下所示:

fun main() {
    val json1 = "{ \"name\": \"Alex\", \"address\": \"rome, 1000\" }"
    val json2 = "{ \"name\": \"Alex\", \"address\": {\"city\": \"rome\", \"post\": \"1000\" } }"

    val gson = GsonBuilder().registerTypeAdapter(Model::class.java, ModelDeserializer()).create()

    println(gson.fromJson(json1, Model::class.java))
    println(gson.fromJson(json2, Model::class.java))
}

data class Model(val name: String, val address: String)

class ModelDeserializer : JsonDeserializer<Model> {

    override fun deserialize(json: JsonElement, typeOfT: Type, context:     JsonDeserializationContext): Model {
        json as JsonObject

        val name = json.get("name").asString

        val addressJson = json.get("address")
        val address = if (addressJson.isJsonObject) addressJson.asJsonObject.toString() else addressJson.asString

        return Model(name, address)
    }
}

哪个输出:

Model(name=Alex, address=rome, 1000)
Model(name=Alex, address={"city":"rome","post":"1000"})

如果您使用的是Kotson库(看起来确实如此),情况将会变得更好:

val gson = GsonBuilder()
        .registerTypeAdapter<Model> {
            deserialize {
                val json = it.json.asJsonObject

                val name = json["name"].asString

                val addressJson = json["address"]
                val address = if (addressJson.isJsonObject) addressJson.asJsonObject.toString() else addressJson.asString

                Model(name, address)
            }
        }
        .create()

println(gson.fromJson<Model>(json1))
println(gson.fromJson<Model>(json2))

答案 2 :(得分:1)

请尝试使用Any,它应该可以工作。

var address: String? = null

答案 3 :(得分:-1)

如果address本身是有效的json,则可以执行以下操作:

val jsonObject = JSONObject(jsonString)
val address = jsonObject.optJSONObject("address").toString()

如果是字符串,则

val address = jsonObject.optString("address").toString()