我有一个 JSon 字符串,我想将它恢复为 Java 对象,其类具有相同的父类。我期望的是创建一些 class 对象AbsNode
,并设置参考图。
我试过的:
//Object node = JSON.parseObject(json, AbsNode.class, Feature.IgnoreAutoType); //node=null
Object node = JSON.parse(json, Feature.IgnoreAutoType); //node is aJsonObject, not AbsNode
System.out.println(node.toString());
但这些都不符合我的要求。那么,使用 FastJson 实现我的目标的正确方法是什么?
Json 字符串是:
{
"@type":".GuardNode",
"worker":{
"@type":"AI.DirectNode",
"key":"worker1",
"val":1
},
"fallback":{
"@type":"AI.GuardNode",
"worker":{
"@type":"AI.DirectNode",
"key":"worker2",
"val":2
},
"fallback":{
"@type":"AI.GuardNode",
"worker":{
"@type":"AI.DirectNode",
"key":"worker3",
"val":3
},
"fallback":{
"@type":"AI.GuardNode",
"worker":{
"@type":"AI.DirectNode",
"key":"worker4",
"val":4
},
"fallback":{
"@type":"AI.DirectNode",
"key":"worker5",
"val":5
}
}
}
}
}
和课程:
public abstract class AbsNode {
public abstract NodeResult execute();
}
@AllArgsConstructor
@Data
public class DirectNode extends AbsNode {
@JSONField(name = "key")
String key;
@JSONField(name = "val")
int val;
}
@AllArgsConstructor
@Data
public class GuardNode extends AbsNode {
@JSONField(name = "worker")
AbsNode worker;
@JSONField(name = "fallback")
AbsNode fallback;
}
@AllArgsConstructor
@Data
public class ParallelNode<T> extends AbsNode {
@JSONField(name = "workers")
List<AbsNode> workers;
@JSONField(name = "weights")
List<Double> weights;
}
生成Graph的源代码:
DirectNode worker1 = new DirectNode("worker1", 1);
DirectNode worker2 = new DirectNode("worker2", 2);
DirectNode worker3 = new DirectNode("worker3", 3);
DirectNode worker4 = new DirectNode("worker4", 4);
DirectNode worker5 = new DirectNode("worker5", 5);
AbsNode l1 = new GuardNode(worker4, worker5);
AbsNode l2 = new GuardNode(worker3, l1);
AbsNode l3 = new GuardNode(worker2, l2);
AbsNode root = new GuardNode(worker1, l3);
String json =
JSON.toJSONString(root, SerializerFeature.WRITE_MAP_NULL_FEATURES, SerializerFeature.WriteClassName);