为什么在序列化内置类型时会忽略JsonAdapter注释?

时间:2015-09-09 00:11:38

标签: java json gson

问题

想象一下以下字段:

@JsonAdapter(CustomTypeAdapter.class)
private int field;

反序列化时,CustomTypeAdapter的{​​{1}}方法会照常调用,但在序列化时,{{1完全忽略了方法,并且内置类型按照通常的方式写出。 (如果我使用read而不是write,也会发生同样的事情。)

问题

我在the documentation中找不到任何说明这是预期行为的内容。是吗?或者这是一个错误吗?

解决方法

我能找到的唯一解决方法是创建一个自定义"持有者"输入然后公开,例如,

Integer

这有效,但有点麻烦。

1 个答案:

答案 0 :(得分:2)

虽然我同意它不适用于int,但我无法在Gson 2.3.1中重现 }的行为。首先,您必须使用TypeAdapter<Integer>(或Integer)而不是TypeAdapterFactory。它在JsonAdapter Javadoc中具体说明了。

  

此注释引用的类必须是TypeAdapterTypeAdapterFactory。使用工厂界面可以委派给封闭的JsonSerializer实例。

然后,类型自动装箱,因此如果要使用注释,则该字段必须为Gson。在玩具示例中将这两个事实结合起来(同样,Integer将不起作用),我们有:

int

输出:

import java.io.IOException;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

public class JsonAdapterExample {
  public static void main(String[] args) {
    Gson g = new Gson();

    System.out.println(g.toJson(new Car()));
  }

  public static class Car {
    @JsonAdapter(IdAdapter.class)
    Integer id = 10;
  }

  public static class IdAdapter extends TypeAdapter<Integer> {
    @Override
    public Integer read(JsonReader arg0) throws IOException {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    public void write(JsonWriter arg0, Integer arg1) throws IOException {
      arg0.beginObject();
      arg0.name("id");
      arg0.value(String.valueOf(arg1));
      arg0.endObject();
    } 
  }
}

如果它不起作用,它将是{"id":{"id":"10"}} 而不是10,并且没有内部对象。

相关问题