GSON 没有为接口类型调用我的 TypeAdapter
GSON似乎正在做某种技巧,它查看我的JavaBeans的内部字段,而不是使用可公开访问的属性信息。不幸的是,这对我们来说不会飞,因为我们神奇创造的豆子充满了私人领域,我不希望它储存起来。
@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;
}
}
这给出了:
{"privateStuff":"secret","name":"Alice"}
当然,永远不要调用我的类型适配器,这似乎使得不可能获得任何其他行为。