Skip to content

Support for canonical JSON output in Jackson. #3963

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package tools.jackson.databind.ser;

import java.math.BigDecimal;

import tools.jackson.core.JacksonException;
import tools.jackson.core.JsonGenerator;
import tools.jackson.databind.SerializerProvider;
import tools.jackson.databind.ser.std.StdSerializer;

public class CanonicalBigDecimalSerializer extends StdSerializer<BigDecimal>
implements ValueToString<BigDecimal> {

public static final CanonicalBigDecimalSerializer INSTANCE = new CanonicalBigDecimalSerializer();

public static final CanonicalNumberSerializerProvider PROVIDER = new CanonicalNumberSerializerProvider() {
@Override
public StdSerializer<BigDecimal> getNumberSerializer() {
return INSTANCE;
}

@Override
public ValueToString<BigDecimal> getValueToString() {
return INSTANCE;
}
};

protected CanonicalBigDecimalSerializer() {
super(BigDecimal.class);
}

@Override
public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider provider)
throws JacksonException {
CanonicalNumberGenerator.verifyBigDecimalRange(value, provider);

String output = convert(value);
gen.writeNumber(output);
}

@Override
public String convert(BigDecimal value) {
// TODO Convert to exponential form if necessary
BigDecimal stripped = value.stripTrailingZeros();
int scale = stripped.scale();
String text = stripped.toPlainString();
if (scale == 0) {
return text;
}

int pos = text.indexOf('.');
int exp;
if (pos >= 0) {
exp = pos - 1;

if (exp == 0) {
return text;
}

text = text.substring(0, pos) + text.substring(pos + 1);
} else {
exp = -scale;
int end = text.length();
while (end > 0 && text.charAt(end - 1) == '0') {
end --;
}
text = text.substring(0, end);
}

if (text.length() == 1) {
return text + 'E' + exp;
}

return text.substring(0, 1) + '.' + text.substring(1) + 'E' + exp;
}
Copy link
Member

@JooHyukKim JooHyukKim Jun 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there an existing reference to this implementation or newly created? I think we can use some methods within BigDecimal itself, or JDK methods like java.text.DecimalFormat to simplify the conversion.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I created this from scratch since I couldn't find anything suitable on the classpath.

The toString() methods in BigDecimal itself don't work (they either don't print an exponent or print only some numbers with exponent) and DecimalFormat has weird quirks (like being not thread safe which might or might not cause problems). There are other implementations of DecimalFormat in some Apache commons library but I didn't want to add new dependencies.

This class only exists because https://gibson042.github.io/canonicaljson-spec/ requires it. Personally, I would always print the number in a readable form without exponent OR as an integer with a negative exponent (so it can always be parsed without any rounding errors).

I would be grateful for advice how to proceed here.

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package tools.jackson.databind.ser;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.math.BigDecimal;

import org.junit.jupiter.api.Test;

public class CanonicalBigDecimalSerializerTest {

@Test
void testCanonicalDecimalHandling_1() throws Exception {
assertSerialized("1", new BigDecimal("1"));
}

@Test
void testCanonicalDecimalHandling_1_000() throws Exception {
assertSerialized("1", new BigDecimal("1.000"));
}

@Test
void testCanonicalDecimalHandling_10_1000() throws Exception {
assertSerialized("1.01E1", new BigDecimal("10.1000"));
}

@Test
void testCanonicalDecimalHandling_1000() throws Exception {
assertSerialized("1E3", new BigDecimal("1000"));
}

@Test
void testCanonicalDecimalHandling_0_00000000010() throws Exception {
assertSerialized("0.0000000001", new BigDecimal("0.00000000010"));
}

@Test
void testCanonicalDecimalHandling_1000_00010() throws Exception {
assertSerialized("1.0000001E3", new BigDecimal("1000.00010"));
}

@Test
void testCanonicalHugeDecimalHandling() throws Exception {
BigDecimal actual = new BigDecimal("123456789123456789123456789123456789.123456789123456789123456789123456789123456789000");
assertSerialized("1.23456789123456789123456789123456789123456789123456789123456789123456789123456789E35", actual);
}

private void assertSerialized(String expected, BigDecimal actual) {
CanonicalBigDecimalSerializer serializer = new CanonicalBigDecimalSerializer();
assertEquals(expected, serializer.convert(actual));
}

}
31 changes: 31 additions & 0 deletions src/test/java/tools/jackson/databind/ser/CanonicalJsonFactory.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package tools.jackson.databind.ser;

import java.io.Writer;
import java.math.BigDecimal;

import tools.jackson.core.JacksonException;
import tools.jackson.core.JsonGenerator;
import tools.jackson.core.ObjectWriteContext;
import tools.jackson.core.io.IOContext;
import tools.jackson.core.json.JsonFactory;

/**
* TODO Fix double numbers. This feels like a very heavy solution plus I can't
* use the JsonFactory.builder().
*/
public class CanonicalJsonFactory extends JsonFactory {
private static final long serialVersionUID = 1L;

private ValueToString<BigDecimal> _serializer;

public CanonicalJsonFactory(ValueToString<BigDecimal> serializer) {
this._serializer = serializer;
}

@Override
protected JsonGenerator _createGenerator(ObjectWriteContext writeCtxt, IOContext ioCtxt, Writer out)
throws JacksonException {
JsonGenerator delegate = super._createGenerator(writeCtxt, ioCtxt, out);
return new CanonicalNumberGenerator(delegate, _serializer);
}
}
48 changes: 48 additions & 0 deletions src/test/java/tools/jackson/databind/ser/CanonicalJsonMapper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package tools.jackson.databind.ser;

import tools.jackson.core.StreamWriteFeature;
import tools.jackson.databind.MapperFeature;
import tools.jackson.databind.SerializationFeature;
import tools.jackson.databind.json.JsonMapper;

public class CanonicalJsonMapper { // TODO It would be great if we could extend JsonMapper but the return type of builder() is incompatible

public static class Builder { // TODO Can't extend MapperBuilder<JsonMapper, Builder> because that needs JsonFactory as ctor arg and we only have this later
private CanonicalNumberSerializerProvider _numberSerializerProvider = CanonicalBigDecimalSerializer.PROVIDER;
private boolean _enablePrettyPrinting = false;

private Builder() {
// Don't allow to create except via builder method
}

public Builder prettyPrint() {
_enablePrettyPrinting = true;
_numberSerializerProvider = PrettyBigDecimalSerializer.PROVIDER;
return this;
}

public JsonMapper build() {
CanonicalJsonFactory jsonFactory = new CanonicalJsonFactory(_numberSerializerProvider.getValueToString());
CanonicalJsonModule module = new CanonicalJsonModule(_numberSerializerProvider.getNumberSerializer());

JsonMapper.Builder builder = JsonMapper.builder(jsonFactory)
.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS) //
.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY) //
.addModule(module);

if (_enablePrettyPrinting) {
builder = builder //
.enable(SerializationFeature.INDENT_OUTPUT) //
.enable(StreamWriteFeature.WRITE_BIGDECIMAL_AS_PLAIN) //
.defaultPrettyPrinter(CanonicalPrettyPrinter.INSTANCE) //
;
}

return builder.build();
}
}

public static CanonicalJsonMapper.Builder builder() {
return new Builder();
}
}
18 changes: 18 additions & 0 deletions src/test/java/tools/jackson/databind/ser/CanonicalJsonModule.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package tools.jackson.databind.ser;

import java.math.BigDecimal;

import tools.jackson.databind.module.SimpleModule;
import tools.jackson.databind.ser.std.StdSerializer;

public class CanonicalJsonModule extends SimpleModule {
private static final long serialVersionUID = 1L;

public CanonicalJsonModule() {
this(CanonicalBigDecimalSerializer.INSTANCE);
}

public CanonicalJsonModule(StdSerializer<BigDecimal> numberSerializer) {
addSerializer(BigDecimal.class, numberSerializer);
}
}
Loading