gpt4 book ai didi

serialization - Kotlin 数据类使用 GSON 动态创建其字段的 json

转载 作者:搜寻专家 更新时间:2023-11-01 08:19:19 25 4
gpt4 key购买 nike

我有一个这样的数据类:

data class TestModel(
val id: Int,
val description: String,
val picture: String)

如果我使用 GSON 从这个数据类创建 JSON,它会生成这样的结果

{"id":1,"description":"Test", "picture": "picturePath"}

如果我需要来 self 的数据类的以下 JSON,该怎么办:

{"id":1, "description":"Test"}

其他时候:

`{"id":1, "picture": "picturePath"}

`提前致谢!

最佳答案

您可以通过编写自定义适配器和可选类型来解决这个问题:

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter

data class TestModel(
val id: Int,
val description: String? = "",
val picture: String? = "")

class TesModelTypeAdapter : TypeAdapter<TestModel>() {
override fun read(reader: JsonReader?): TestModel {
var id: Int? = null
var picture: String? = null
var description: String? = null

reader?.beginObject()
while (reader?.hasNext() == true) {
val name = reader.nextName()

if (reader.peek() == JsonToken.NULL) {
reader.nextNull()
continue
}

when (name) {
"id" -> id = reader.nextInt()
"picture" -> picture = reader.nextString()
"description" -> description = reader.nextString()
}
}
reader?.endObject()

return when {
!picture.isNullOrBlank() && description.isNullOrBlank() -> TestModel(id = id ?: 0, picture = picture)
!description.isNullOrBlank() && picture.isNullOrBlank() -> TestModel(id = id ?: 0, description = description)
else -> TestModel(id ?: 0, picture, description)
}
}

override fun write(out: JsonWriter?, value: TestModel?) {
out?.apply {
beginObject()

value?.let {
when {
!it.picture.isNullOrBlank() && it.description.isNullOrBlank() -> {
name("id").value(it.id)
name("picture").value(it.picture)
}
!it.description.isNullOrBlank() && it.picture.isNullOrBlank() -> {
name("id").value(it.id)
name("description").value(it.description)
}
else -> {
name("id").value(it.id)
name("picture").value(it.picture)
name("description").value(it.description)
}
}
}

endObject()
}
}
}

class App {
companion object {
@JvmStatic fun main(args: Array<String>) {
val tm = TestModel(12, description = "Hello desc")
val tm2 = TestModel(23, picture = "https://www.pexels.com/photo/daylight-forest-glossy-lake-443446/")
val tm3 = TestModel(12, "Hello desc", "https://www.pexels.com/photo/daylight-forest-glossy-lake-443446/")

val gson = GsonBuilder().registerTypeAdapter(TestModel::class.java, TesModelTypeAdapter()).create()

System.out.println(gson.toJson(tm))
System.out.println(gson.toJson(tm2))
System.out.println(gson.toJson(tm3))
}
}
}

enter image description here

关于serialization - Kotlin 数据类使用 GSON 动态创建其字段的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53500502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com