[Simple-support] Multiple custom boolean formats using @Convert
Brought to you by:
niallg
|
From: <ses...@al...> - 2011-06-28 08:36:27
|
Hi all,
I'm dealing with some inconsistent XML that I must parse. See below:
<example tfBool="true" ynBool="Y" />
You can see that the tfBool attribute will be parsed properly, but the ynBool attribute needs special conversion. Here's my attempted solution:
@Root
public class Example {
private static String testXML = "<example tfBool=\"true\" ynBool=\"Y\" />";
@Attribute
public boolean tfBool;
@Attribute
@Convert(Example.YesNoBooleanConverter.class)
public boolean ynBool;
public static class YesNoBooleanConverter implements Converter<Boolean> {
public Boolean read(InputNode node) throws Exception {
return new Boolean(node.getValue().equals("Y"));
}
public void write(OutputNode node, Boolean value) throws Exception {
node.setValue(value.booleanValue()?"Y":"N");
}
}
public static void main(String[] args) throws Exception {
Serializer s = new Persister(new AnnotationStrategy());
Example e = s.read(Example.class, new StringReader(testXML));
System.out.println("tfBool = " + e.tfBool);
System.out.println("ynBool = " + e.ynBool);
}
}
This code does not work. The output is:
tfBool = true
ynBool = false
As far as I can tell, YesNoBooleanConverter is never used. I'm assuming that it's because the boolean primitive type already matches to an existing Transformer implementation, so there's no way to use @Convert to use a custom converter if it's already mapped by the PrimitiveMatcher.
I can't use my own custom Transform/Match setup in this case, because the implementation is inconsistent (and as far as I can tell, this also eliminates the RegistryStrategy as an option as well). If all boolean values were represented by "Y" and "N", then I could set up a Matcher for boolean and put together a Transform that converts between strings properly. I need to convert standard boolean string representations for the first attribute and custom boolean string representations for the second.
Is there any way to do this easily (without having to have a custom converter for the whole class, for example)?
Owen |