在 Pair.of() 中:你能改变(S 第一,T 第二)的名字吗?

In Pair.of() : Can you change the name of(S first, T second)?

{
            "first": "1.0",
            "second": "Not Predicted"
        },
        {
            "first": "1.1",
            "second": "Not Predicted"
        }

Pair.of的表示是:Pair of(S first,T second) 那么这里是否可以将默认名称 firstsecond 更改为我们希望保留的名称?

杰克逊的解决方案:

声明特定class对

的序列化器
public static class PairSerializer extends StdSerializer<Pair> {

    public PairSerializer() {
        this(null);
    }

    public PairSerializer(Class<Pair> t) {
        super(t);
    }

    @Override
    public void serialize(Pair value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeObjectField("a", value.getFirst());   // "a" is replacement for "first"
        jgen.writeObjectField("b", value.getSecond());  // "b" is replacement for "second"
        jgen.writeEndObject();
    }
}

然后您注册这个序列化程序并将您的 Pair(s) 序列化为 JSON

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Pair.class, new PairSerializer());
mapper.registerModule(module);

List<Pair<String, String>> pairs = Arrays.asList(Pair.of("1.0", "Unpredicted"), Pair.of("1.1", "Unpredicted"));

System.out.println(mapper.writeValueAsString(pairs));

输出:

[
  {
    "a": "1.0",
    "b": "Unpredicted"
  },
  {
    "a": "1.1",
    "b": "Unpredicted"
  }
]