Skip to content
This repository was archived by the owner on Jan 22, 2019. It is now read-only.

Commit aceb22e

Browse files
committed
Merge pull request #27 from osi/2.6
support serialization of BigDecimal values
2 parents ac01d01 + a482465 commit aceb22e

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/main/java/com/fasterxml/jackson/dataformat/avro/ser/NonBSGenericDatumWriter.java

+22
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
package com.fasterxml.jackson.dataformat.avro.ser;
22

3+
import java.io.IOException;
4+
import java.math.BigDecimal;
35
import java.util.List;
46

57
import org.apache.avro.Schema;
68
import org.apache.avro.Schema.Type;
79
import org.apache.avro.generic.GenericDatumWriter;
10+
import org.apache.avro.io.Encoder;
811

912
/**
1013
* Need to sub-class to prevent encoder from crapping on writing an optional
@@ -36,8 +39,27 @@ public int resolveUnion(Schema union, Object datum) {
3639
default:
3740
}
3841
}
42+
} else if( datum instanceof BigDecimal) {
43+
List<Schema> schemas = union.getTypes();
44+
for (int i = 0, len = schemas.size(); i < len; ++i) {
45+
Schema s = schemas.get(i);
46+
switch (s.getType()) {
47+
case DOUBLE:
48+
return i;
49+
default:
50+
}
51+
}
3952
}
4053
// otherwise just default to base impl, stupid as it is...
4154
return super.resolveUnion(union, datum);
4255
}
56+
57+
@Override
58+
protected void write(Schema schema, Object datum, Encoder out) throws IOException {
59+
if(schema.getType() == Type.DOUBLE && datum instanceof BigDecimal) {
60+
out.writeDouble(((BigDecimal)datum).doubleValue());
61+
} else {
62+
super.write(schema, datum, out);
63+
}
64+
}
4365
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.fasterxml.jackson.dataformat.avro;
2+
3+
import com.fasterxml.jackson.annotation.JsonCreator;
4+
import com.fasterxml.jackson.annotation.JsonProperty;
5+
import junit.framework.TestCase;
6+
import org.junit.Test;
7+
8+
import java.math.BigDecimal;
9+
10+
11+
public class BigDecimalTest extends TestCase {
12+
13+
@Test
14+
public void testSSerializeBigDecimal() throws Exception {
15+
AvroMapper mapper = new AvroMapper();
16+
AvroSchema schema = mapper.schemaFor(NamedAmount.class);
17+
18+
byte[] bytes = mapper.writer(schema)
19+
.writeValueAsBytes(new NamedAmount("peter", 42.0));
20+
21+
NamedAmount result = mapper.reader(schema).forType(NamedAmount.class).readValue(bytes);
22+
23+
assertEquals("peter", result.name);
24+
assertEquals(BigDecimal.valueOf(42.0), result.amount);
25+
}
26+
27+
public static class NamedAmount {
28+
public final String name;
29+
public final BigDecimal amount;
30+
31+
@JsonCreator
32+
public NamedAmount(@JsonProperty("name") String name,
33+
@JsonProperty("amount") double amount) {
34+
this.name = name;
35+
this.amount = BigDecimal.valueOf(amount);
36+
}
37+
38+
39+
}
40+
}

0 commit comments

Comments
 (0)