Reputation: 2603
Good day, let's say I have class Person:
@Root(name="Person")
public class Person {
@Element(name="Name")
public String name = "MyName"
@ElementList(name="AddressList", entry="Address", required=false)
public ArrayList<Address> addressList = new ArrayList<>();
}
... and class Address:
public class Address {
@Element(name="Street")
public String street;
@Element(name="City")
public String city;
}
When addressList has no items Simple produces this XML:
<Person>
<Name>MyName</Name>
<AddressList/>
</Person>
Please, how can I make Simple omit tag AddressList if there are no items on the list? I want the XML look like this in such case:
<Person>
<Name>MyName</Name>
</Person>
Thank you in advance.
UPDATE: I forgot to mention that I don't want to set the addressList to null. When I create Person object I want the addressList to be initialized so that I can easily add addresses if needed and I don't need to check whehter it is null and instantiate it. The example above is very simple but when my object hierarchy is more complicated it is unconvenient to check and initialize all lists. So I hoped I could resolve it using some anotation or custom converter.
Upvotes: 0
Views: 467
Reputation: 7189
Use the @Resolve and @Replace annotations, here you can do.
@Replace
private Object writeReplace() {
return new InstanceWithANullList();
}
and then
@Resolve
private Object readResolve() {
return new InstanceWithANonNullList();
}
Upvotes: 1
Reputation: 11
I think assigning null to the List will work, if that is an option for you...
OK as this is not an option maybe something like
public void addCustomer(Customer c) {
if (this.customerList == null) {
this.customerList = new ArrayList<Customer>();
}
customerList.add(c);
}
might do the trick?
Not assigning null will alwas result in an empty tag in XML, I think. That's what makes the difference between null and an empty List.
Upvotes: 1