Skip to content

test case for serializing custom numbers with config overrides #5199

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

Open
wants to merge 2 commits into
base: 2.x
Choose a base branch
from
Open
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
Expand Up @@ -117,6 +117,12 @@ public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider se
}
}

static class MyBigDecimal extends BigDecimal {
public MyBigDecimal(String value) {
super(value);
}
}

/*
/**********************************************************
/* Test methods
Expand Down Expand Up @@ -222,6 +228,24 @@ public void testCustomSerializationBigDecimalAsNumber() throws Exception {
assertEquals(a2q("{'value':2.0}"), mapper.writeValueAsString(new BigDecimalHolder("2")));
}

@Test
public void testConfigOverrideJdkNumber() throws Exception {
ObjectMapper mapper = jsonMapperBuilder().withConfigOverride(BigDecimal.class,
c -> c.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING)))
.build();
String value = mapper.writeValueAsString(new BigDecimal("123.456"));
assertEquals(a2q("'123.456'"), value);
}

@Test
public void testConfigOverrideNonJdkNumber() throws Exception {
ObjectMapper mapper = jsonMapperBuilder().withConfigOverride(MyBigDecimal.class,
Copy link
Member

Choose a reason for hiding this comment

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

Arguably should work with override for BigDecimal, not impl type. But probably depends on exactly how Jackson registers relevant serializer (its handledType()) so becomes sort of implementation detail.

But if this is how things currently work, we'll go with that.

c -> c.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING)))
.build();
String value = mapper.writeValueAsString(new MyBigDecimal("123.456"));
assertEquals(a2q("'123.456'"), value);
}

// default locale is en_US
static DecimalFormat createDecimalFormatForDefaultLocale(final String pattern) {
return new DecimalFormat(pattern, new DecimalFormatSymbols(Locale.ENGLISH));
Expand Down