在我的Java项目中,使用Hibernate,我有两个bean (这里只显示相关属性) :
public class Project {
private int projectId;
private String property1;
// ...
@JsonSerialize(using=MyOwnSerializer.class)
@JsonDeserialize(using=MyOwnDeserializer.class)
private List<ProjectItem> items;
}
public class ProjectItem {
private String code;
private String value;
private String stuff;
private Project project;
}
如您所见,项目有一个项目列表,每个项目都绑定到一个项目。为了简化我的前端应用程序,我自己序列化列表以获得这样的JSON,以避免在我想访问一个代码时迭代整个列表:
{ "projectId": 12345,
"property1": "foo",
"items": {"code1": {"value": "foo", "stuff": "bar"},
"code2": {"value": "baz", "stuff": "abc"},
...
}
}
我想要的是在反序列化(JSON到POJO)中设置Project
引用。我现在所做的是:
// From MyOwnDeserializer
public List<ProjectItem> deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.readValueAsTree();
// Read property
Iterator<String> it = node.fieldNames();
ArrayList<ProjectItem> lst = new ArrayList<ProjectItem>();
while(it.hasNext()) {
String code = it.next();
JsonNode subnode = node.findValue(code);
ProjectItem obj = new ProjectItem();
obj.setCode(code);
obj.setValue(getStringOrNull(subnode, "value")); // own function which returns
// ... // null or a String, nothing special
// So far, I can't call setProject() (I don't have any
// reference to the parent), so project is still null.
lst.add(obj);
}
return lst;
}
现在,我正在寻找的是:如何在反序列化中翻译项目引用,即项目的父对象?。如果需要,我可以将projectId放在我的JSON中。
我通过调试器查看了ctxt
对象,我可以在Project
HashMap中看到我的_objectIds
对象,但我无法真正访问它...