GSON不会为接口的类型调用我的TypeAdapter [英] GSON not calling my TypeAdapter for a type which is an interface
本文介绍了GSON不会为接口的类型调用我的TypeAdapter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@Test
public void testJson()抛出异常
{
Player player = new MagicPlayer(); //BeanUtils.createDefault(Player.class);
player.setName(Alice);
Gson gson = new GsonBuilder()
.registerTypeAdapter(Player.class,new PlayerTypeAdapter())
.create();
System.out.println(gson.toJson(bean));
}
private static class PlayerTypeAdapter实现了JsonSerializer< Player>
{
@Override
public JsonElement serialize(Player player,Type type,
JsonSerializationContext context)
{
throw new RuntimeException(哇噢);
public static interface Player // extends SupportsPropertyChanges
{
public String getName();
public void setName(String name);
}
//简单的实现模拟我们正在做的事情。
public static class MagicPlayer implements Player
{
private final String privateStuff =secret;
私人字符串名称;
@Override
public String getName()
{
return name;
}
@Override
public void setName(String name)
{
this.name = name;
$ / code $ / pre
$ b $ p 这给出:
{privateStuff:secret,name:Alice}
当然,从来不会调用我的类型适配器,这似乎使得不可能发生任何其他行为。 方案
我有同样的问题,与当前版本的gson(2.3.1)并通过使用
.registerTypeHierarchyAdapter(Player.class,new PlayerTypeAdapter())
p>
.registerTypeAdapter(Player.class,new PlayerTypeAdapter())
GSON appears to be doing some kind of trick where it looks at the internal fields of my JavaBeans instead of using the publically-accessible property information. Unfortunately this won't fly for us because our magically-created beans are full of private fields which I don't want it to store off.
@Test
public void testJson() throws Exception
{
Player player = new MagicPlayer(); //BeanUtils.createDefault(Player.class);
player.setName("Alice");
Gson gson = new GsonBuilder()
.registerTypeAdapter(Player.class, new PlayerTypeAdapter())
.create();
System.out.println(gson.toJson(bean));
}
private static class PlayerTypeAdapter implements JsonSerializer<Player>
{
@Override
public JsonElement serialize(Player player, Type type,
JsonSerializationContext context)
{
throw new RuntimeException("I got called, woohoo");
}
}
public static interface Player //extends SupportsPropertyChanges
{
public String getName();
public void setName(String name);
}
// Simple implementation simulating what we're doing.
public static class MagicPlayer implements Player
{
private final String privateStuff = "secret";
private String name;
@Override
public String getName()
{
return name;
}
@Override
public void setName(String name)
{
this.name = name;
}
}
This gives:
{"privateStuff":"secret","name":"Alice"}
And of course, never calls my type adapter, which seemingly makes it impossible to get any other behaviour.
解决方案
I had the same issue, with the current version of gson (2.3.1) and got it working by using
.registerTypeHierarchyAdapter(Player.class, new PlayerTypeAdapter())
instead of
.registerTypeAdapter(Player.class, new PlayerTypeAdapter())
这篇关于GSON不会为接口的类型调用我的TypeAdapter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文