Last active
June 16, 2020 18:53
-
-
Save Fubuchi/6cb9c33a235393ea2ed702778058b65b to your computer and use it in GitHub Desktop.
Jackson Serializer for Apache Pair class with custom field name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Getter | |
@AllArgsConstructor | |
@NoArgsConstructor | |
public class ComplexData { | |
private int id; | |
@JsonSerialize(using = PairSerializer.class) | |
// if left == right, R will overwrite L in the json result | |
@PairIdentify(left = "anyName1", right = "anyName2") | |
private Pair<L, R> data; // L, R is any type | |
@JsonSerialize(contentUsing = PairSerializer.class) // use contentUsing for collection | |
@PairIdentify(left = "anyName1", right = "anyName2") | |
private List<Pair<L, R>> colelctionData; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Retention(RetentionPolicy.RUNTIME) | |
@Target(ElementType.FIELD) | |
public @interface PairIdentify { | |
String left() default "left"; | |
String right() default "right"; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@AllArgsConstructor // https://projectlombok.org/ | |
@NoArgsConstructor | |
@SuppressWarnings({ "squid:S3740", "rawtypes" }) | |
public class PairSerializer extends JsonSerializer<Pair> implements ContextualSerializer { | |
private String left = "left"; | |
private String right = "right"; | |
@Override | |
public void serialize(Pair value, JsonGenerator gen, SerializerProvider serializer) throws IOException { | |
gen.writeStartObject(); | |
gen.writeObjectField(left, value.getLeft()); | |
gen.writeObjectField(right, value.getRight()); | |
gen.writeEndObject(); | |
} | |
@Override | |
public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property) { | |
return Optional.ofNullable(property.getAnnotation(PairIdentify.class)) | |
.map(ann -> new PairSerializer(ann.left(), ann.right())) | |
.orElseGet(PairSerializer::new); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment