I currently am working with Jackson to read an XML file from an online location, map it to an object and then insert that object into MongoDB using the Object Mapper.
At the moment my dataset looks something like this:
<sensors>
<sensor id="000" name="Sensor Name" refreshRate="2000">
<location latitude="12.3456" longitude="-67.890"/>
</sensor>
<sensor id="000" name="Sensor Name" refreshRate="2000">
<location latitude="12.3456" longitude="-67.890"/>
</sensor>
</sensors>
If I do the following:
List entries = xmlMapper.readValue(conn.getInputStream(), List.class);
I get back a list of LinkedHashMap that contain the items. However, I would much prefer if I could just map this back to my Sensor Class that I've already created.
This sensor class is the one I use when interacting with Mongo and it looks something like this:
@Document(collection = "Sensor")
@JsonIgnoreProperties(ignoreUnknown = true)
@JacksonXmlRootElement(localName="sensors")
public class Sensor {
@Id
private int id;
String name = "";
long refreshRate = "";
Location location;
...
}
I've tried casting or mapping to Sensor; however, that doesn't work. What is the missing step? All documentation and tutorials I read up on only seem to handle simple instances of a single entry.
While you are using generic List, I guess Map is default representation of your data.
If you want to tell to the mapper, how your data should be represented, I would use something like this:
List<Sensor> entries = xmlMmapper.readValue(conn.getInputStream(), new TypeReference<List<Sensor>>() {});
I cannot verify if this compiles at this moment, but I hope it helps.
For more info about TypeReference, see here.