7

我在一个项目中使用 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);
    }

});
4

3 回答 3

10

回答完整性

使用 convert 注释来注释你的元素,并给它一个转换器类作为参数 @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);
    }

}

并且不要添加new AnnotationStrategy()到您的持久化器中。

于 2011-04-18T06:22:49.570 回答
2

使用属性注释。它有一个名为 empty 的属性,用于提供默认值。

请参阅简单框架 Javadocs。

于 2011-04-13T12:19:55.987 回答
-1

我是否完全认为它应该是一个空字符串而不是空字符串?

据我所知……通常这表明序列化过程中存在一些问题,它应该返回对象,并且它是非瞬态实例变量,其值设置在序列化上。

顺便说一句,您没有发布所有代码,序列化开始的顺序也可能意味着它跳过了字符串数据,这有时可能是一个问题。

于 2011-04-13T12:19:57.630 回答