I am using XStream with Annotations to go between my Java objects and XML. I am essentially trying to make the XML as minimal as possible, and one the items I want to reduce is the inclusion of boolean
values when not necessary. When a boolean
value is false
I do not want to include it in my xml, since it's default value is also false.
Is there away to configure XSream to not include values when they are equal to their default values?
Given:
public class Test {
@XStreamAlias("name")
@XStreamAsAttribute
private String name;
@XStreamAlias("good")
@XStreamAsAttribute
private boolean good;
public Test(String name, boolean good){
this.name = name;
this.good = good;
}
public static void main(String[] args) {
XStream stream = new XStream();
stream.processAnnotations(new Class[] {Test.class});
Test test1 = new Test("Test", true);
System.out.println(stream.toXML(test1));
Test test2 = new Test("Test", false);
System.out.println(stream.toXML(test2));
}
}
This prints:
<Test name="Test" good="true"/>
<Test name="Test" good="false"/>
I want it to be:
<Test name="Test" good="true"/>
<Test name="Test"/>
Edit:
I noticed BooleanConverter has a method called shouldConvert
so I tried overriding that by extending the class. Which did not work, it is never called. The method:
@Override
public boolean shouldConvert(Class type, Object value) {
System.out.println("Class: "+type+" Value: "+value);
return (Boolean)value;
}
My variable annotation to set the converter on good
@XStreamConverter(MyBooleanConverter.class)
@XStreamAlias("good")
@XStreamAsAttribute
private boolean good;
You have to write your own BooleanConverter
overriding the toString(Objec obj)
method.
public class MyBooleanConverter extends BooleanConverter{
@Override
public String toString(Object obj) {
if(((Boolean)obj).equals(false)){
return null;
}
return super.toString(obj);
}
}
Then set the Annotation to use the converter on the variable that you want:
@XStreamConverter(MyBooleanConverter.class)
@XStreamAlias("good")
@XStreamAsAttribute
private boolean good;
That works but requires you to set add the annotation in XStreamConverter every single time. I would prefer to not have to do that, since I want my converter to be used much more frequently than the default. You can use registerConverter
to accomplish that. Here is the complete example:
public class Test {
@XStreamAlias("name")
@XStreamAsAttribute
private String name;
@XStreamAlias("good")
@XStreamAsAttribute
private boolean good;
public Test(String name, boolean good){
this.name = name;
this.good = good;
}
public static void main(String[] args) {
XStream stream = new XStream();
stream.processAnnotations(new Class[] {Test.class});
stream.registerConverter(new MyBooleanConverter());
Test test1 = new Test("Test", true);
System.out.println(stream.toXML(test1));
Test test2 = new Test("Test", false);
System.out.println(stream.toXML(test2));
}
}