oop - 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)
解决方案
推荐阅读
- javascript - 使用 typeScript 获取本地 JSON 文件。我在静态页面中遇到跨源错误
- php - 使用 Laravel assertDatabaseHas 和浮点列进行单元测试
- python - Dialogflow 查询 HTTP 请求
- vba - 将文件夹中所有文件的数据复制并粘贴到同一文件夹中的主文件
- javascript - 如何将二进制视频数据保存到 azure blob?
- python - 将熊猫列的一部分复制到同一列的其他部分?
- python-3.x - 未找到 Python 但可以安装
- matlab - 如何提取信号的单个波分量信息?
- scala - 为什么使用多个参数列表定义折叠?
- c# - Json.net:不要将数字反序列化为布尔值