Skip to content

Fix serialization of union types at root level (fixes #168) #169

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 1 commit 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
Expand Up @@ -163,6 +163,28 @@ public final String toString()

// // // Shared helper methods

protected GenericRecord _createRecord(Schema schema, Object currValue) throws JsonMappingException
{
Type type = schema.getType();
if (type == Schema.Type.UNION) {
try {
schema = resolveUnionSchema(schema, currValue);
} catch (UnresolvedUnionException e) {
// couldn't find an exact match
schema = _recordOrMapFromUnion(schema);
}
}
if (type == Schema.Type.MAP) {
throw new IllegalStateException("_createRecord should never be called for elements of type MAP");
}
try {
return new GenericData.Record(schema);
} catch (RuntimeException e) {
// alas, generator not passed to us
throw new JsonMappingException(null, "Failed to create Record type from "+type, e);
}
}

protected GenericRecord _createRecord(Schema schema) throws JsonMappingException
{
// Quick check: if type is Union, need to find actual record type...
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public final AvroWriteContext createChildObjectContext(Object currValue) throws
case RECORD:
case UNION: // maybe
{
GenericRecord rec = _createRecord(_schema);
GenericRecord rec = _createRecord(_schema, currValue);
_rootValue = rec;
return new ObjectWriteContext(this, _generator, rec, currValue);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,15 @@ public boolean equals(Object o) {
}
}

@Test
public void testRootUnionWithAnimal() throws IOException {
Cat cat = new Cat("meow");
//
Cat result = roundTrip(Animal.class, cat);
//
assertThat(result).isEqualTo(cat);
}

@Test
public void testInterfaceUnionWithCat() throws IOException {
Cage cage = new Cage(new Cat("test"));
Expand Down