我在一个项目中使用 simpleframework ( http://simple.sourceforge.net/ ) 来满足我的序列化/反序列化需求,但是在处理空/空字符串值时它不能按预期工作(好吧,至少不是我期望的那样) .
如果我用空字符串值序列化一个对象,它将显示为一个空的 xml 元素。
所以这:
MyObject object = new MyObject();
object.setAttribute(""); // attribute is String
将序列化为:
<object>
<attribute></attribute>
</object>
但是反序列化该空属性最终会为空,而不是空字符串。
我是否完全认为它应该是一个空字符串而不是空字符串?我到底怎样才能让它以我不想的方式工作?
哦,如果我用 null 属性序列化对象,它最终
<object/>
会按预期显示。
编辑:
添加了一个我正在运行的简单测试用例
@Test
public void testDeserialization() throws Exception {
StringWriter writer = new StringWriter();
MyDTO dto = new MyDTO();
dto.setAttribute("");
Serializer serializer = new Persister();
serializer.write(dto, writer);
System.out.println(writer.getBuffer().toString());
MyDTO read = serializer.read(MyDTO.class, writer.getBuffer().toString(),true);
assertNotNull(read.getAttribute());
}
@Root
public class MyDTO {
@Element(required = false)
private String attribute;
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
}
编辑,修复:
由于某种原因,InputNode
当将空字符串传递给它时,该值为 null。我通过为String
.
new Converter<String>() {
@Override
public String read(InputNode node) throws Exception {
if(node.getValue() == null) {
return "";
}
return node.getValue();
}
@Override
public void write(OutputNode node, String value) throws Exception {
node.setValue(value);
}
});