Skip to content

Commit

Permalink
JavaBeanConverter: Always serialize fields with null values, fixes #5.
Browse files Browse the repository at this point in the history
  • Loading branch information
rkreis committed May 10, 2015
1 parent 4f55641 commit faa89f7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.javabean.BeanProvider;
import com.thoughtworks.xstream.converters.javabean.JavaBeanProvider;
import com.thoughtworks.xstream.converters.reflection.MissingFieldException;
import com.thoughtworks.xstream.core.util.FastField;
import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper;
Expand Down Expand Up @@ -78,6 +80,8 @@ public void visit(final String propertyName, final Class<?> fieldType, final Cla
final Object newObj) {
if (newObj != null) {
writeField(propertyName, fieldType, newObj, definedIn);
} else {
writeNullField(propertyName);
}
}

Expand All @@ -94,6 +98,13 @@ private void writeField(final String propertyName, final Class<?> fieldType, fin

writer.endNode();
}

private void writeNullField(final String propertyName) {
final String serializedMember = mapper.serializedMember(source.getClass(), propertyName);
ExtendedHierarchicalStreamWriterHelper.startNode(writer, serializedMember, Mapper.Null.class);
writer.addAttribute(classAttributeName, mapper.serializedClass(Mapper.Null.class));
writer.endNode();
}
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,19 @@ public void setAShortClass(Short shortClass) {
}
}

public void testRoundtripWithNullValue() {
World world = new World();
world.setAString(null);

XStream xstream = new XStream();
xstream.registerConverter(new JavaBeanConverter(xstream.getMapper(), new BeanProvider(
new StringComparator())), XStream.PRIORITY_LOW);
xstream.allowTypes(World.class);

World world2 = (World) xstream.fromXML(xstream.toXML(world));
assertEquals(null, world2.getAString());
}

public void testSerializesAllPrimitiveFieldsInACustomObject() {
World world = new World();

Expand Down

0 comments on commit faa89f7

Please sign in to comment.