Re: [Simple-support] erialize/deserialize Lists with empty Strings
Brought to you by:
niallg
|
From: Joe <fis...@ya...> - 2008-12-16 16:14:38
|
Hi,
> So it looks like if you really need the empty string
> "" then you will need to either treat null as a special case, or
> substitute "" for some token such as "NULL".
I think i will use a slightly different approach, inspired by the base64
encoding example in your tutorial.
I encode every value with a prefix (here '*') only null values are ignored.
So
Arrays.asList("A", "", null)
will be serialized as:
<testData>
<_values class="java.util.Arrays$ArrayList">
<string>*A</string>
<string>*</string>
<string></string>
</_values>
</testData>
Using @Commit the deserialization can be adjusted, to getting back
the original values.
The output of the following example is the expected String:
values: [A, , null]
public class TestData
{
@ElementList()
private List<String> _values = new ArrayList<String>();
public List<String> getValues()
{
return _values;
}
public void setValues(List<String> values)
{
_values = values;
}
@Persist
public void persist()
{
for (int i = 0; i < _values.size(); i++)
if (_values.get(i) != null)
_values.set(i, "*" + _values.get(i));
else
_values.set(i, "");
}
@Commit
public void commit()
{
for (int i = 0; i < _values.size(); i++)
{
String val = _values.get(i);
if (val != null)
_values.set(i, _values.get(i).substring(1));
}
}
public static void main(String[] args) throws Exception
{
Serializer serializer = new Persister();
File xmlFile = new File("test.xml");
TestData data = new TestData();
data.setValues(Arrays.asList("A", "", null));
serializer.write(data, xmlFile);
TestData sqlData = serializer.read(TestData.class, xmlFile);
System.out.println("values: " + sqlData.getValues());
}
}
|