首页 > 解决方案 > Kotlin GSON 自定义反序列化

问题描述

我有一个我正在尝试反序列化的 JSON。我正在尝试使用以下约束来适应以下结构

1) rectangle 和 Square 都是 Shape 类型,并且可以有一个 Shapes 列表。

2)它们的顺序可以切换一个Square可以有一个矩形列表(形状列表)

3) Square 和 Rectangle 也可以有一个 Circle 列表,它不从 Shape 继承任何东西,并且基本上由 Shape 组成

4)我想唯一标识正方形和矩形类,并且在我的模型结构中反序列化后不将它们视为相同的 Shape 对象(想知道是否有方法不解析 type 属性,所以我知道对象类型是 Square 或 Rectangle)。

{
 "type": "rectangle",
 "x": "3",
 "y": "3",
"children": [
{
  "type": "square",
  "x": "3",
  "y": "4",
  "children": [
    {
      "type": "circle",
      "radius": "3"
    },
    {
      "type": "circle",
      "radius": "4"
    },
    {
      "type": "circle",
      "radius": "5"
    }
  ]
}
]
}

到目前为止我创建的模型对象

abstract class Shape {
abstract val x: String
abstract val y: String
abstract val type: String
abstract val children: List<Shape>
}

data class Square(override val x: String, override val y: String, override val type: String, 
  override val children: List<Shape>) : Shape()

data class Rectangle(override val x: String, override val y: String, override val type: 
   String, override val children: List<Shape>) : Shape()

data class Circle(val radius: String, val type: String)

标签: oopkotlingsonjson-deserialization

解决方案


推荐阅读