如何在kotlin中解析json文件。在互联网上有很多解决方案,但是它们都是相同的,但是我无法在kotlin中找到解析我的json文件的方法。
我的json文件
{
"A": [
{
"collocation": "above average",
"meaning": "more than average, esp. in amount, age, height, weight etc. "
},
{
"collocation": "absolutely necessary",
"meaning": "totally or completely necessary"
},
{
"collocation": "abuse drugs",
"meaning": "to use drugs in a way that's harmful to yourself or others"
},
{
"collocation": "abuse of power",
"meaning": "the harmful or unethical use of power"
}
],
"B": [
{
"collocation": "back pay",
"meaning": "money a worker earned in the past but hasn't been paid yet "
},
{
"collocation": "back road",
"meaning": "a small country road "
},
{
"collocation": "back street",
"meaning": "a street in a town or city that's away from major roads or central areas"
},
{
"collocation": "back taxes",
"meaning": "taxes that weren't paid when they were due"
},
{
"collocation": "bad breath",
"meaning": "breath that doesn't smell nice"
}],这样就可以达到字母W。
我想用信来分析它们。
我的数据类
data class Collocations(
val tag:String,
val collocation: List<Collocation>
)
data class Collocation(
val collocation: String,
val meaning: String
)但我认为这些数据类在我看来是不正确的,或者是无效的。
发布于 2022-11-14 17:26:56
您应该只需要这里提供的Collocation类。然后顶层对象可以是一个Map<String, List<Collocation>>,因此字母可以是动态键。
使用Kotlinx序列化,它可以如下所示:
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
@Serializable
data class Collocation(
val collocation: String,
val meaning: String,
)
fun main() {
val json: String = TODO("get your JSON string here")
val collocations = Json.decodeFromString<Map<String, List<Collocation>>>(json)
val collocationsForA = collocations["A"]
println(collocationsForA)
}https://stackoverflow.com/questions/74434688
复制相似问题