我正在尝试使用gson类型适配器来反序列化我的JSON。我可以将对象反序列化,但type属性总是返回null。
JSON:
{
"type": "rectangle",
"x": "3",
"y": "3",
"description": "this is my battle ground",
"children": [
{
"type": "square",
"x": "3",
"y": "4",
"description": "this is my arena",
"children": [
{
"type": "circle",
"x": "0",
"y": "0",
"radius": "3",
"description": "this is my inner circle"
},
{
"type": "circle",
"x": "0",
"y": "0",
"radius": "4",
"description": "this is my inner circle"
},
{
"type": "circle",
"x": "0",
"y": "0",
"radius": "5",
"description": "this is my inner circle"
}
]
}
]
}型号:
abstract class Shape {
abstract val type: String
abstract val x: String
abstract val y: String
abstract val description: String
}
abstract class ShapeChildren : Shape() {
abstract val children: List<Shape>
}
enum class ShapeType(val type: String) {
SQUARE("square"),
RECTANGLE("rectangle"),
CIRCLE("circle")
}
data class Square(override val type: String, override val x: String, override val y: String, override val description: String, override val children: List<Shape>) : ShapeChildren()
data class Rectangle(override val type: String, override val x: String, override val y: String, override val description: String, override val children: List<Shape>) : ShapeChildren()
data class Circle(override val type: String, override val x: String, override val y: String, override val description: String, val radius: String) : Shape()配置GSON:
val jsonResponse = loadFile("mock-response/shape.json")
val adapterFactory = RuntimeTypeAdapterFactory.of(Shape::class.java)
.registerSubtype(ShapeChildren::class.java)
.registerSubtype(Square::class.java, "square")
.registerSubtype(Circle::class.java, "circle")
.registerSubtype(Rectangle::class.java, "rectangle")
val gson = GsonBuilder()
.registerTypeAdapterFactory(adapterFactory)
.create()
val shape = gson.fromJson(jsonResponse, Shape::class.java)
print(shape)输出:
Rectangle(type=null, x=3, y=3, description=this is my battle ground, children=[Square(type=null, x=3, y=4, description=this is my arena, children=[Circle(type=null, x=0, y=0, description=this is my inner circle, radius=3), Circle(type=null, x=0, y=0, description=this is my inner circle, radius=4), Circle(type=null, x=0, y=0, description=this is my inner circle, radius=5)])])对于子类,type属性始终为null。我甚至尝试通过在构造函数中给它一个默认值来设置它。为什么类型属性不能正确填充?我遗漏了什么?
发布于 2020-05-07 20:26:17
只需使用RuntimeTypeAdapterFactory.of(Shape::class.java, "type", true)而不是RuntimeTypeAdapterFactory.of(Shape::class.java)。最后一个参数是maintainType。您将其设置为false,在这种情况下,类型属性将在反序列化之前从json中删除。
https://stackoverflow.com/questions/60796054
复制相似问题