[英]How to serialize/deserialize a DefaultMutableTreeNode with Jackson?
[英]How to serialize DefaultMutableTreeNode (Java) to JSON?
如何將樹(使用DefaultMutableTreeNode
類在Java中實現)序列化為JSON(用於通過RESTful方法傳輸到iOS客戶端)?
我試過了:
String jsonString = (new Gson()).toJson(topNode);
// topNode is DefaultMutableTreeNode at the root
它崩潰與StackOverflowError
。
Swing的DefaultMutableTreeNode
類是一個類似樹的數據結構,其中包含與children
和parent
相同類型的實例。 這就是Gson的默認序列化程序遇到無限遞歸並因此引發StackOverflowError
。
要解決此問題,您需要使用專門設計用於將DefaultMutableTreeNode
轉換為JSON的更智能的JsonSerializer
來定制Gson
。 另外,您可能還想提供一個JsonDeserializer
用於將此類JSON轉換回DefaultMutableTreeNode
。
為此,不僅要通過new Gson()
創建Gson
實例,還要通過
Gson gson = new GsonBuilder()
.registerTypeAdapter(DefaultMutableTreeNode.class, new DefaultMutableTreeNodeSerializer())
.registerTypeAdapter(DefaultMutableTreeNode.class, new DefaultMutableTreeNodeDeserializer())
.setPrettyPrinting()
.create();
下面的DefaultMutableTreeNodeSerializer
負責將DefaultMutableTreeNode
轉換為JSON。 它將其屬性allowsChildren
, userObject
和children
為JSON。 請注意,它不會將parent
屬性轉換為JSON,因為這樣做會再次產生無限遞歸。
public class DefaultMutableTreeNodeSerializer implements JsonSerializer<DefaultMutableTreeNode> {
@Override
public JsonElement serialize(DefaultMutableTreeNode src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("allowsChildren", src.getAllowsChildren());
jsonObject.add("userObject", context.serialize(src.getUserObject()));
if (src.getChildCount() > 0) {
jsonObject.add("children", context.serialize(Collections.list(src.children())));
}
return jsonObject;
}
}
為了進行測試,讓我們將示例JTree
的根節點序列化為JSON,然后再次將其反序列化。
JTree tree = new JTree(); // create a sample tree
Object topNode = tree.getModel().getRoot(); // a DefaultMutableTreeNode
String jsonString = gson.toJson(topNode);
System.out.println(jsonString);
DefaultMutableTreeNode topNode2 = gson.fromJson(jsonString, DefaultMutableTreeNode.class);
它生成以下JSON輸出:
{
"allowsChildren": true,
"userObject": "JTree",
"children": [
{
"allowsChildren": true,
"userObject": "colors",
"children": [
{
"allowsChildren": true,
"userObject": "blue"
},
{
"allowsChildren": true,
"userObject": "violet"
},
{
"allowsChildren": true,
"userObject": "red"
},
{
"allowsChildren": true,
"userObject": "yellow"
}
]
},
{
"allowsChildren": true,
"userObject": "sports",
"children": [
{
"allowsChildren": true,
"userObject": "basketball"
},
{
"allowsChildren": true,
"userObject": "soccer"
},
{
"allowsChildren": true,
"userObject": "football"
},
{
"allowsChildren": true,
"userObject": "hockey"
}
]
},
{
"allowsChildren": true,
"userObject": "food",
"children": [
{
"allowsChildren": true,
"userObject": "hot dogs"
},
{
"allowsChildren": true,
"userObject": "pizza"
},
{
"allowsChildren": true,
"userObject": "ravioli"
},
{
"allowsChildren": true,
"userObject": "bananas"
}
]
}
]
}
下面的DefaultMutableTreeNodeDeserializer
負責將JSON轉換回DefaultMutableTreeNode
。
它使用與如何使用Jackson序列化/反序列化DefaultMutableTreeNode中的反序列化器相同的思想。 。 DefaultMutableTreeNode
不是非常類似於POJO,因此不能與Gson一起很好地工作。 因此,它使用行為良好的POJO
幫助器類(具有屬性allowsChildren
, userObject
和children
),並讓Gson將JSON內容反序列化到此類中。 然后,將POJO
對象(及其POJO
子對象)轉換為DefaultMutableTreeNode
對象(具有DefaultMutableTreeNode
子對象)。
public class DefaultMutableTreeNodeDeserializer implements JsonDeserializer<DefaultMutableTreeNode> {
@Override
public DefaultMutableTreeNode deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
return context.<POJO>deserialize(json, POJO.class).toDefaultMutableTreeNode();
}
private static class POJO {
private boolean allowsChildren;
private Object userObject;
private List<POJO> children;
// no need for: POJO parent
public DefaultMutableTreeNode toDefaultMutableTreeNode() {
DefaultMutableTreeNode node = new DefaultMutableTreeNode();
node.setAllowsChildren(allowsChildren);
node.setUserObject(userObject);
if (children != null) {
for (POJO child : children) {
node.add(child.toDefaultMutableTreeNode()); // recursion!
// this did also set the parent of the child-node
}
}
return node;
}
// Following setters needed by Gson's deserialization:
public void setAllowsChildren(boolean allowsChildren) {
this.allowsChildren = allowsChildren;
}
public void setUserObject(Object userObject) {
this.userObject = userObject;
}
public void setChildren(List<POJO> children) {
this.children = children;
}
}
}
這是對我的較早答案的一種改進的替代方法,該較早的答案對DefaultMutableTreeNode
使用JsonSerializer
和JsonDeserializer
實現。 這兩個接口的API文檔說:
新應用程序應該首選
TypeAdapter
,其流API比此接口的樹API更高效。
因此,讓我們使用這種首選方法,並為DefaultMutableTreeNode
實現TypeAdapter
。
使用它,您可以像這樣創建Gson
實例(而不是僅使用new Gson()
):
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(DefaultMutableTreeNodeTypeAdapter.FACTORY)
.setPrettyPrinting()
.create();
下面的DefaultMutableTreeNodeTypeAdapter
負責將DefaultMutableTreeNode
與JSON相互轉換。 它寫入/讀取其屬性allowsChildren
, userObject
和children
。 無需編寫parent
屬性,因為父子關系已經在JSON輸出的嵌套結構中進行了編碼。
public class DefaultMutableTreeNodeTypeAdapter extends TypeAdapter<DefaultMutableTreeNode> {
public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
@Override
@SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (type.getRawType() == DefaultMutableTreeNode.class) {
return (TypeAdapter<T>) new DefaultMutableTreeNodeTypeAdapter(gson);
}
return null;
}
};
private final Gson gson;
private DefaultMutableTreeNodeTypeAdapter(Gson gson) {
this.gson = gson;
}
@Override
public void write(JsonWriter out, DefaultMutableTreeNode node) throws IOException {
out.beginObject();
out.name("allowsChildren");
out.value(node.getAllowsChildren());
out.name("userObject");
gson.toJson(node.getUserObject(), Object.class, out);
if (node.getChildCount() > 0) {
out.name("children");
gson.toJson(Collections.list(node.children()), List.class, out); // recursion!
}
// No need to write node.getParent(), it would lead to infinite recursion.
out.endObject();
}
@Override
public DefaultMutableTreeNode read(JsonReader in) throws IOException {
in.beginObject();
DefaultMutableTreeNode node = new DefaultMutableTreeNode();
while (in.hasNext()) {
switch (in.nextName()) {
case "allowsChildren":
node.setAllowsChildren(in.nextBoolean());
break;
case "userObject":
node.setUserObject(gson.fromJson(in, Object.class));
break;
case "children":
in.beginArray();
while (in.hasNext()) {
node.add(read(in)); // recursion!
// this did also set the parent of the child-node
}
in.endArray();
break;
default:
in.skipValue();
break;
}
}
in.endObject();
return node;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.