【发布时间】:2022-01-15 23:37:24
【问题描述】:
我有一个名为Component 的类,其中包含一些属性,包括Device 类的对象,它是某些类的基类,例如Resistance 和M1,我必须读取组件的JSON 文件并检查设备的类型Resistance 或M1 然后将其映射到正确的类我尝试使用 JSON 注释但我仍然收到错误!
这是我的课程 组件类:
public class Component {
private String type;
private String id;
@JsonProperty
private Device device;
@JsonProperty("netlist")
private HashMap<String,String> netlist;
public Component() {
}
public Component(String type, String id, Device device, HashMap<String, String> netList) {
this.type = type;
this.id = id;
this.device = device;
this.netlist = netList;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Device getDevice() {
return device;
}
public void setDevice(Device device) {
this.device = device;
}
public HashMap<String, String> getNetlist() {
return netlist;
}
public void setNetlist(HashMap<String, String> netlist) {
this.netlist = netlist;
}
@Override
public String toString() {
return "type='" + type + '\'' +
", id='" + id + '\'' +
", "+device.toString()+
", netList=" + netlist ;
}
}
设备类:
public abstract class Device {
@JsonProperty("default")
protected int defaultValue;
protected int min;
protected int max;
public Device() {
}
public Device(int defaultValue, int min, int max) {
this.defaultValue = defaultValue;
this.min = min;
this.max = max;
}
public int getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(int defaultValue) {
this.defaultValue = defaultValue;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
}
阻力:
@JsonTypeName("resistance")
public class Resistance extends Device {
public Resistance() {
}
@Override
public String toString() {
return "resistance{" +
"default=" + defaultValue +
", min=" + min +
", max=" + max +
'}';
}
}
M1 类:
@JsonTypeName(value = "m(1)")
public class M1 extends Device {
@Override
public String toString() {
return "m(1){" +
"default=" + defaultValue +
", min=" + min +
", max=" + max +
'}';
}
}
这是一个简单的 JSON 文件:
"components": [
{
"type": "resistor",
"id": "res1",
"resistance": {
"default": 100,
"min": 10,
"max": 1000
},
"netlist": {
"t1": "vdd",
"t2": "n1"
}
},
{
"type": "nmos",
"id": "m1",
"m(l)": {
"deafult": 1.5,
"min": 1,
"max": 2
},
"netlist": {
"drain": "n1",
"gate": "vin",
"source": "vss"
}
}
]
提前致谢
【问题讨论】:
标签: java json spring-boot binding jackson