-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
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
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
75 changes: 75 additions & 0 deletions
75
src/test/java/tools/jackson/databind/ser/CanonicalBigDecimalSerializer.java
This file contains hidden or 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
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; | ||
} | ||
} |
52 changes: 52 additions & 0 deletions
52
src/test/java/tools/jackson/databind/ser/CanonicalBigDecimalSerializerTest.java
This file contains hidden or 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
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
31
src/test/java/tools/jackson/databind/ser/CanonicalJsonFactory.java
This file contains hidden or 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
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
48
src/test/java/tools/jackson/databind/ser/CanonicalJsonMapper.java
This file contains hidden or 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
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
18
src/test/java/tools/jackson/databind/ser/CanonicalJsonModule.java
This file contains hidden or 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
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); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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 likejava.text.DecimalFormat
to simplify the conversion.There was a problem hiding this comment.
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 ofDecimalFormat
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.