I have to write a message handler that will process incoming XML messages and pass them on to another module as JSON representations. There are a relatively high of possible messages and I would rather use a single POJO for my purpose. Here is an example XML message.
<Message name="GenericMsg">
<StartTime>533798131</StartTime> <!-- Unix Timestamp -->
.
.
<!-- Some other fields -->
.
<NumberOfItems>2</NumberOfItems>
<List>
<ListItem>
<Speed>100</Speed>
<Location>
<lat>38.165748</lat>
<lon>37.125363</lon>
<alt>800</alt>
</Location>
</ListItem>
<ListItem>
<Speed>120</Speed>
<Location>
<lat>39.123748</lat>
<lon>41.312645</lon>
<alt>850</alt>
</Location>
</ListItem>
</List>
</Message>
And my POJO
public class MsgRepr {
private Map<String, Object> details = new LinkedHashMap<>();
public Object get(String key) {
return this.details.get(key);
}
@JsonAnyGetter
public Map<String, Object> getDetails() {
return this.details;
}
@JsonAnySetter
public void setDetails(String key, Object value) {
this.details.put(key,value);
}
}
This gets converted to the following JSON:
{
"name" : "GenericMsg",
"NumberOfItems" : "2",
"StartTime" : "533798131"
"List" : {
"ListItem" :
[
{
"Speed" : "100",
"Location" : {
"lat" : "38.165748",
"lon" : "37.125363",
"alt" : "800"
}
},
{
"Speed" : "150",
"Location" : {
"lat" : "48.564866",
"lon" : "35.18795",
"alt" : "850"
}
}
]
}
}
I tried the defaultUseWrapper=false
option with no avail. Also, omitting the List/ListItem duality results in only the last element being present.
I know that this can be done by writing a seperate POJO for each message, but I would rather avoid doing that. Is there an alternative XML representation or an alternative approach I can use to correctly convert the json to something similar to the following format?
{
"name" : "GenericMsg",
"NumberOfItems" : "2",
"StartTime" : "533798131"
"List" :
[
{
"Speed" : "100",
"Location" : {
"lat" : "38.165748",
"lon" : "37.125363",
"alt" : "800"
}
},
{
"Speed" : "150",
"Location" : {
"lat" : "48.564866",
"lon" : "35.18795",
"alt" : "850"
}
}
]
}
Jackson version 2.13.0