我正在尝试使用jackson库序列化和反序列化嵌套的对象列表。我可以用所需的格式成功地序列化它,但很难将它反序列化回POJO。
范围:
@AllArgsConstructor
public class Scope {
@Getter
private List<TypeObjectPair> scope;
}
TypeObjectPair:
@AllArgsConstructor
public class TypeObjectPair {
private final String canonicalName;
private final Object object;
@JsonIgnore
public Object getObject() {
return object;
}
/**
* Defines non-static and no-argument method as "any getter". It behaves as an accessor for getting a set of key-value pairs. @JsonAnyGetter must return a Java Map
*/
@JsonAnyGetter
public Map<String, Object> getData() {
return ImmutableMap.of(canonicalName, object);
}
}
的TestObject:
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Random;
public class TestUtils {
public static TestObject generateRandomTestObject(){
Random random = new Random();
return new TestObject(random.nextInt(), random.nextInt(), random.nextInt());
}
@AllArgsConstructor
@Getter
public static class TestObject{
private final Integer foo;
private final Integer bar;
private final Integer zar;
}
}
输入序列化:
TestUtils.TestObject testObject1 = TestUtils.generateRandomTestObject();
TestUtils.TestObject testObject2 = TestUtils.generateRandomTestObject();
List<Scope> scopes = new ArrayList<>();
scopes.add(new Scope(Arrays.asList(new TypeObjectPair(testObject1.getClass().getCanonicalName(), testObject1))));
scopes.add(new Scope(Arrays.asList(new TypeObjectPair(testObject2.getClass().getCanonicalName(), testObject2))));
输出Json:
我现在有Json。
[
"{\"scope\":[{\"com.example.diagnostic.TestUtils.TestObject\":{\"foo\":-2110569858,\"bar\":459860579,\"zar\":-392750688}},{\"com.example.diagnostic.TestUtils.TestObject\":{\"foo\":728145129,\"bar\":-1001861122,\"zar\":-1906803097}}]}",
"{\"scope\":[{\"com.example.diagnostic.TestUtils.TestObject\":{\"foo\":1911640128,\"bar\":-1827459393,\"zar\":519274751}},{\"com.example.diagnostic.TestUtils.TestObject\":{\"foo\":-1287628009,\"bar\":726563108,\"zar\":2114775662}}]}"
]
将反序列化的最佳和最干净的方法是什么?