您的当前位置:首页正文

java gson序列化_java – Gson多态序列化

2024-11-27 来源:个人技术集锦

使用Gson 2.2.2我正在尝试序列化POJO(行为)的数组列表.

我有一个适配器几乎是我在网上看到的副本:

public class BehaviorAdapter implements JsonSerializer {

private static final String CLASSNAME = "CLASSNAME";

private static final String INSTANCE = "INSTANCE";

@Override

public JsonElement serialize(Behavior src, Type typeOfSrc,

JsonSerializationContext context) {

JsonObject retValue = new JsonObject();

String className = src.getClass().getCanonicalName();

retValue.addProperty(CLASSNAME, className);

JsonElement elem = context.serialize(src);

retValue.add(INSTANCE, elem);

return retValue;

}

}

我这样注册:

GsonBuilder builder = new GsonBuilder();

builder.registerTypeHierarchyAdapter(Behavior.class, new BehaviorAdapter());

gson = builder.create();

然后,当我尝试序列化我的ArrayList时:

String json2 = gson.toJson(behaviors);

我得到一个堆栈溢出.

它似乎在线:

JsonElement elem = context.serialize(src);

它启动一个递归循环,一次又一次地通过我的序列化器.那么如何注册它以便不会发生这种情况?我需要序列化列表并维护多态性.

解决方法:

However, you should never invoke it on the src object itself since that will cause an infinite loop (Gson will call your call-back method again).

我能想到的最简单的方法是创建一个没有安装处理程序的新Gson实例,然后通过它运行实例.

作为最终运行,您可以序列化List< Behavior>代替:

public class BehaviorListAdapter implements JsonSerializer> {

private static final String CLASSNAME = "CLASSNAME";

private static final String INSTANCE = "INSTANCE";

@Override

public JsonElement serialize(List src, Type typeOfSrc,

JsonSerializationContext context) {

JsonArray array = new JsonArray();

for (Behavior behavior : src) {

JsonObject behaviorJson = new JsonObject();

String className = behavior.getClass().getCanonicalName();

behaviorJson.addProperty(CLASSNAME, className);

JsonElement elem = context.serialize(behavior);

behaviorJson.add(INSTANCE, elem);

array.add(behaviorJson);

}

return array;

}

}

GsonBuilder builder = new GsonBuilder();

// use a TypeToken to make a Type instance for a parameterized type

builder.registerTypeAdapter(

(new TypeToken>() {}).getType(),

new BehaviorListAdapter());

gson = builder.create();

标签:java,gson

来源: https://codeday.me/bug/20190713/1450552.html

显示全文