Question

I am using the Simple XML library to serialize a set of elements:

@Root(name = "items")
public class Items {

  @ElementList(required = false, inline = true, entry = "item")
  private Set<Item> items;

  public Set<Item> getItems() {
    return items;
  }

  public void setItems(final Set<Item> items) {
    this.items = items;
  }
}

I need the collection to be a Set, but at the same time it needs to be sorted - for this reason, when serializing, I use LinkedHashSet as the actual type of the items.

Set<Item> items = new LinkedHashSet<Item>();
items.add(...);
items.add(...);
items.add(...);
Items root = new Items();
root.setItems(items);
new Persister().write(root, stringWriter);

This works out just fine and the resulting XML contains the Item elements in the correct order.

The problem is with the deserialization - Simple XML sees that the type is Set, picks an implementation in CollectionFactory.getConversion(): a HashSet, which does not keep the order of the elements.

One way to fix it is to change the definition of Items:

  @ElementList(required = false, inline = true, entry = "item")
  private LinkedHashSet<Item> items;

  public void setItems(final LinkedHashSet<Item> items) {
    this.items = items;
  }

This works, but it's really against good coding practices. Is there a way to tell Simple XML to use LinkedHashSet?

Was it helpful?

Solution

I guess the problem is caused by inlining. If you don't use inline, simple will put all elements as childs into a set-tag. This tag contains e.g. a class="java.util.LinkedHashSet" attribute, what makes it possible to decide the set-implementation.

But this is impossible for an inline-collection, so simple takes a default one.

What you can do:

  1. Use private LinkedHashSet<Item> items; as you've already written - this makes very clear what implementation you want
  2. Use a constructor where you instantiate the implementation: public Items() { this.items = new LinkedHashSet<>(); }
  3. Write a Converter, where you handle the deserialisation by your own (possible an overkill).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top