[英]simpleframework, deserializing an empty element to an empty string instead of null
我在一個項目中使用 simpleframework ( http://simple.sourceforge.net/ ) 來滿足我的序列化/反序列化需求,但是在處理空/空字符串值時它沒有按預期工作(好吧,至少不是我期望的那樣) .
如果我使用空字符串值序列化一個對象,它將顯示為一個空的 xml 元素。
所以這:
MyObject object = new MyObject();
object.setAttribute(""); // attribute is String
將序列化為:
<object>
<attribute></attribute>
</object>
但是反序列化該空屬性最終會為空,而不是空字符串。
我是不是完全瘋了,認為它應該是一個空字符串而不是 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;
}
}
編輯,修復:
出於某種原因,當向InputNode
傳遞空字符串時,它的值為 null。 我通過為String
創建自定義 Converter 解決了這個問題。
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);
}
});
回答完整性
使用 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()
添加到您的持久器中。
使用屬性注釋。 它有一個名為 empty 的屬性,用於提供默認值。
我是不是完全瘋了,認為它應該是一個空字符串而不是 null?
據我所知......通常這表明序列化過程中存在一些問題,它應該返回對象及其所有非瞬態實例變量,其值設置在序列化上。
順便說一句,您沒有發布所有代碼,也可能是序列化開始的順序意味着它跳過了字符串數據,這有時可能是一個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.