simpleframework,将空元素反序列化为空字符串而不是null

San*_*and 7 java serialization deserialization simple-framework

我在项目中使用simpleframework(http://simple.sourceforge.net/)来进行序列化/反序列化需求,但在处理空/ null字符串值时,它不能按预期工作(好吧,至少不是我期望的) .

如果我使用空String值序列化一个对象,它将显示为一个空的xml元素.

所以这
MyObject object = new MyObject();
object.setAttribute(""); // attribute is String

将序列化为
<object>
<attribute></attribute>
</object>

但反序列化该空属性将最终为null,而不是空字符串.

我认为它应该是一个空字符串而不是null,我完全疯了吗?我怎么能以我想要的方式让它工作呢?

哦,如果我使用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;  
    }  
}  
Run Code Online (Sandbox Code Playgroud)

编辑,修复:

由于某种原因,当向其传递空字符串时,InputNode值为null.我通过创建自定义Converter for 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);
    }

});
Run Code Online (Sandbox Code Playgroud)

San*_*and 10

回答完整性

使用转换注释注释元素,并将转换器类作为参数 @Convert(SimpleXMLStringConverter.class)

创建转换器类,该类将字符串从null转换为空字符串

public class SimpleXMLStringConverter implements Converter<String> {


    @Override
    public String read(InputNode node) throws Exception {
        String value = node.getValue();
        if(value == null) {
            value = "";
        }
        return value;
    } 

    @Override
    public void write(OutputNode node, String value) throws Exception {
        node.setValue(value);
    }

}
Run Code Online (Sandbox Code Playgroud)

并且不要为了增加new AnnotationStrategy()你的毅力.