Java simpleframework,将空元素反序列化为空字符串而不是null
我在项目中使用simpleframework()来满足序列化/反序列化的需要,但在处理空/空字符串值时,它并没有像预期的那样工作(至少不是我预期的那样) 如果我用空字符串值序列化对象,它将显示为空xml元素 因此:Java simpleframework,将空元素反序列化为空字符串而不是null,java,serialization,deserialization,simple-framework,Java,Serialization,Deserialization,Simple Framework,我在项目中使用simpleframework()来满足序列化/反序列化的需要,但在处理空/空字符串值时,它并没有像预期的那样工作(至少不是我预期的那样) 如果我用空字符串值序列化对象,它将显示为空xml元素 因此: MyObject object = new MyObject(); object.setAttribute(""); // attribute is String 将序列化为: <object> <attribute></attribute
MyObject object = new MyObject();
object.setAttribute(""); // attribute is String
将序列化为:
<object>
<attribute></attribute>
</object>
编辑,修复:
由于某种原因,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);
}
});
新转换器(){
@凌驾
公共字符串读取(InputNode节点)引发异常{
if(node.getValue()==null){
返回“”;
}
返回node.getValue();
}
@凌驾
公共无效写入(OutputNode节点,字符串值)引发异常{
node.setValue(值);
}
});
使用属性注释。它有一个名为empty的属性,用于提供默认值
请看如果我认为它应该是一个空字符串而不是空字符串,我会彻底疯掉吗 据我所知不是。。。通常这表明序列化过程中存在一些问题,它应该返回对象及其所有非瞬态实例变量,并在序列化时设置值
顺便说一句,您没有发布所有代码,序列化开始的顺序也可能意味着它跳过了字符串数据,这有时可能是个问题。回答完整性问题 使用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);
}
}
公共类SimpleXMLStringConverter实现转换器{
@凌驾
公共字符串读取(InputNode节点)引发异常{
字符串值=node.getValue();
如果(值==null){
value=“”;
}
返回值;
}
@凌驾
公共无效写入(OutputNode节点,字符串值)引发异常{
node.setValue(值);
}
}
不要让get将
新的AnnotationStrategy()
添加到您的持久化程序中。如果我理解正确,@Attribute注释为xml元素创建了一个属性,因此它不会影响元素本身。因此是输入节点导致了它,tx,知道它很有帮助:)
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);
}
}