我有几个包含彼此递归依赖的类,我使用Gson GraphAdapterBuilder将它们序列化为JSON格式,它完美地运行.现在我想将它们反序列化为相同的结构,但无法找到方法.
我做了一个例子:
class ClassA{
public int field;
public ClassB parent;
public ClassA(int f, ClassB p){
field = f;
parent = p;
}
}
class ClassB{
public Vector<ClassA> vector = new Vector<ClassA>();
}
...
ClassB b = new ClassB();
ClassA a1 = new ClassA(1,b);
ClassA a2 = new ClassA(2,b);
ClassA a3 = new ClassA(3,b);
b.vector.add(a1);
b.vector.add(a2);
b.vector.add(a3);
//Serializing object b
GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
.addType(ClassA.class)
.addType(ClassB.class)
.registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();
String json = gson.toJson(b);
Run Code Online (Sandbox Code Playgroud)
输出给了我想要的东西:
{"0x1":{"vector":["0x2","0x3","0x4"]},"0x2":{"field":1,"parent":"0x1"},"0x3":{"field":2,"parent":"0x1"},"0x4":{"field":3,"parent":"0x1"}} …Run Code Online (Sandbox Code Playgroud) 几天来,我一直在寻找“如何在运行时向方法添加注释”的答案,并找到了这个名为 Byte Buddy 的很棒的工具,使用了它,但仍然无法按我的需要工作。我确定它必须能够从这个问题Can Byte Buddy create fields and method annotations at runtime?
有这个类:
public class ClassThatNeedsToBeAnnotated {
public void method(int arg1, String arg2) {
// code that we don't want to touch at all, leave it as is
System.out.println("Called method with arguments " + arg1 + " " + arg2);
}
public void method() {
System.out.println("Called method without arguments");
}
}
Run Code Online (Sandbox Code Playgroud)
和这个代码:
public class MainClass {
public static void main(String[] args) {
ByteBuddyAgent.install();
AnnotationDescription description = AnnotationDescription.Builder.ofType(MyClassAnnotation.class)
.define("value", …Run Code Online (Sandbox Code Playgroud)