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

标签 java json gson

问题

想象一下以下字段:

@JsonAdapter(CustomTypeAdapter.class)
private int field;

反序列化时,CustomTypeAdapterread 方法会照常调用,但序列化时, write 方法被完全忽略,内置类型被写出,就像它通常那样。 (如果我使用 Integer 而不是 int,也会发生同样的事情。)

问题

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

解决方法

我能找到的唯一解决方法是创建一个自定义的“持有人”类型,然后公开它,例如,

@JsonAdapter(CustomTypeAdapter.class)
class CustomType { /* blah blah */ }

private CustomType field;

public int getField() {
    return field.getValue();
}

public void setField(int field) {
    this.field = new CustomType(field);
}

这可行,但有点麻烦。

最佳答案

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

The class referenced by this annotation must be either a TypeAdapter or a TypeAdapterFactory. Using the factory interface makes it possible to delegate to the enclosing Gson instance.

然后,类型不会自动装箱,所以如果你想使用注释,该字段必须是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不是"10" ,并且没有内部对象。

关于java - 为什么在序列化内置类型时会忽略 JsonAdapter 注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32469056/

相关文章:

java - 如何使用 Jackson 将 "name" "value"对的 JSON 数组反序列化为 Pojo

java - 在 Java Applet 中绘制字符串 ArrayList

java - 添加数据作为参数后,Jtable 内容不会刷新

c# - System.Text.Json反序列化错误System.MemoryExtensions无法加载System.Runtime.CompilerServices.Unsafe

php - 如何将while循环中的三个不同变量放入json数组中

android - Gson toJson 将 "\n"添加到我的属性(property)的末尾

performance - jackson 和 gson 之间的 json 解析性能

java - 如何解析使用 GSON 转义引号的 JSON

java - Android Studio 滑动到不同的 View

java - Web 应用程序中的图像在重新部署之前不会显示?