Solution for Jackson:
Declare serializer for specific class Pair
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();
}
}
then you register this serializer and serialize your Pair(s) into 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));
Output:
[
{
"a": "1.0",
"b": "Unpredicted"
},
{
"a": "1.1",
"b": "Unpredicted"
}
]
1
solved In Pair.of() : Can you change the name of(S first, T second)? [closed]