Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tuhin47/5443d0335de1a92787e2f5bc1cc9256d to your computer and use it in GitHub Desktop.
Save tuhin47/5443d0335de1a92787e2f5bc1cc9256d to your computer and use it in GitHub Desktop.
Java Json Serialize/deserialize Converter

Serialize

@JsonSerialize

@JsonSerialize(converter = DoubleAmountConverter.class)
private Double grandTotal;

DoubleAmountConverter.java

public class DoubleAmountConverter extends StdConverter<Double, String> {
    DecimalFormat df = new DecimalFormat("#.00");

    @Override
    public String convert(Double value) {
        return df.format(value);
    }
}

DeSerializer

@JsonDeserialize

@JsonDeserialize(using = InstantTimeDeserializer.class)
private Instant createdAt;

InstantTimeDeserializer.java

public class InstantTimeDeserializer extends JsonDeserializer<Instant> {
    @Override
    public Instant deserialize(JsonParser arg0, DeserializationContext arg1) throws IOException {
        return Instant.parse(arg0.getText());
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment