I have an XML document with many Entity
elements, which each have an attribute of either type="foo"
or type="bar"
. See this sample:
<RootNode>
<Entities>
<Entity type="foo">
<Price>1</Price>
</Entity>
<Entity type="bar">
<URL>www.google.co.uk</URL>
</Entity>
<Entity type="foo">
<Price>77</Price>
</Entity>
</Entities>
</RootNode>
I need a way to tell Simple to deserialize the Entity
elements with type="foo"
into a List<FooEntity>
and the elements with type="bar"
into a List<BarEntity>
.
How can I do this?
Here is the code I currently have if you want to play around with it:
public class App {
public static void main(String[] args) throws Exception {
Reader r = Files.newBufferedReader(
Paths.get("/path/to/file.xml"),
Charset.defaultCharset()
);
Serializer serializer = new Persister();
RootNode root = serializer.read(RootNode.class, r);
System.out.println(root.getFooEntities().size());
System.out.println(root.getBarEntities().size());
}
}
@Root(name = "RootNode")
class RootNode {
// TODO: What annotations to put here?
private List<FooEntity> fooEntities;
// TODO: What annotations to put here?
private List<BarEntity> barEntities;
public List<FooEntity> getFooEntities() { return fooEntities; }
public List<BarEntity> getBarEntities() { return barEntities; }
}
class FooEntity {
@Element(name = "URL")
private String url;
}
class BarEntity {
@Element(name = "Price")
private int price;
}
Now the real problem ...
My answer: none! Or at least, it doesn't matter!
Attributes like
type
here are just strings and can't make any decisions. But there's another nice way:RootNode
which does the decisionSerializer
to do the actual work of deserializing each entity.I made some modifications to your classes, but nothing spectacular has been changed. The
toString()
-method is for testing only - implement as you need it.Class
FooEntity
Class
BarEntity
Class
RootNode
And finally the
Converter
-implementation:Class
RootNodeConverter
There are some things to optimize, eg. add a
root.addBar(ser.read(BarEntity.class, child))
or errorhandling in general.Btw. instead of two lists, you can maintain a single one (if relevant). Just make a superclass for the entities. You can move the
type
-attribute to there too.Usage
Here's an example how to use:
Nothing really spectacular here too ...
Output: