我有以下两个Jsons
"attrs": {
"rect": {
"fill": "blue"
},
"text": {
"fill": "white",
"text": "my box"
}
}
和
"attrs": {
"circle": {
"fill": "red"
},
"text": {
"text": "my circle",
"fill": "yellow"
}
}
有没有一种在解析时将JSON反序列化为特定类(即
class Rect
和class Circle
)的方法?我正在使用Gson 2.4这就是我现在所说的:
Element[] element = gson.fromJson(arguments.toJson(), Element[].class);
而Element类具有这种结构
public class Element {
private Attributes attr;
public class Attributes{
private Rectangle rect;
private Circle circle;
}
如何告诉gson选择其中一个字段?现在,其中之一将为空,我不希望那样,因为我将拥有更多的形状。
最佳答案
如果“ circle”或“ rect”始终是第一个孩子,则可以编写简单的if else
逻辑以确定用于反序列化的类。