{
"first": "1.0",
"second": "Not Predicted"
},
{
"first": "1.1",
"second": "Not Predicted"
}
The representation of Pair.of is : Pair<S, T> of(S first,T second) So here is it possible to change the default names first and second to something we wish to keep ?
CodePudding user response:
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"
}
]