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

support serialization of BigDecimal values #27

Merged
merged 1 commit into from
Nov 25, 2015
Merged
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
@@ -1,10 +1,13 @@
package com.fasterxml.jackson.dataformat.avro.ser;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.io.Encoder;

/**
* Need to sub-class to prevent encoder from crapping on writing an optional
Expand Down Expand Up @@ -36,8 +39,27 @@ public int resolveUnion(Schema union, Object datum) {
default:
}
}
} else if( datum instanceof BigDecimal) {
List<Schema> schemas = union.getTypes();
for (int i = 0, len = schemas.size(); i < len; ++i) {
Schema s = schemas.get(i);
switch (s.getType()) {
case DOUBLE:
return i;
default:
}
}
}
// otherwise just default to base impl, stupid as it is...
return super.resolveUnion(union, datum);
}

@Override
protected void write(Schema schema, Object datum, Encoder out) throws IOException {
if(schema.getType() == Type.DOUBLE && datum instanceof BigDecimal) {
out.writeDouble(((BigDecimal)datum).doubleValue());
} else {
super.write(schema, datum, out);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.fasterxml.jackson.dataformat.avro;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import junit.framework.TestCase;
import org.junit.Test;

import java.math.BigDecimal;


public class BigDecimalTest extends TestCase {

@Test
public void testSSerializeBigDecimal() throws Exception {
AvroMapper mapper = new AvroMapper();
AvroSchema schema = mapper.schemaFor(NamedAmount.class);

byte[] bytes = mapper.writer(schema)
.writeValueAsBytes(new NamedAmount("peter", 42.0));

NamedAmount result = mapper.reader(schema).forType(NamedAmount.class).readValue(bytes);

assertEquals("peter", result.name);
assertEquals(BigDecimal.valueOf(42.0), result.amount);
}

public static class NamedAmount {
public final String name;
public final BigDecimal amount;

@JsonCreator
public NamedAmount(@JsonProperty("name") String name,
@JsonProperty("amount") double amount) {
this.name = name;
this.amount = BigDecimal.valueOf(amount);
}


}
}