I’m trying to use MOXy to generate a specifically formatted response for a front end client to make it easier for them to determine specific relationships. This is a bit of a contrived example, but I’m trying to do something like the following…
public class Person {
private Integer id;
private String name;
private Address address;
}
public class Address {
private String street;
private String locality;
private String state;
private String zip;
}
public class PersonCollectionResponse {
private Set<Person> people;
public Set<Person> getPeople() {
return this.people;
}
private int getCount() {
return this.people.size();
}
}
…and would like to end up with a result like…
{
"meta": {
"count": 2
},
"people": [{
"id": 1,
"name": "Danny Parker",
"contact": {
"locality": "Zoo York",
"state": "New York"
},
}, {
"id": 2,
"name": "Oscar the Grouch",
"contact": {
"locality": "San Francisco",
"state": "California"
}
}],
"mappings": [{
"person": 1,
"zip": 10014
}, {
"person": 2,
"zip": 94102
}]
}
Now the “people” set isn’t very hard, but I’m stuck on how to get the mappings to work when writing the EclipseLink OXM metadata. I’m looking for a way to redefine how people get listed so that I can get my mapping.
<xml-element java-attribute="people">
<xml-element java-attribute="id" xml-path="@id" />
<xml-element java-attribute="zip" xml-path="@zip" />
</xml-element>
Not I get that might now be possible. So I created a getMappings on the PersonCollectionResponse that returns a List> that it generates from the people. Now this isn’t ideal, but there are worse things. But when it is written out, the map objects are strings like so…
"mappings": ["{person: 1, zip: 10014}", "{person: 2, zip: 94102}"]
So I guess my questions are one of these…
- How can I display an element a second time but with a different output?
- How can I output maps without them being quoted as strings?
Worst case scenario I guess is I make my set of generic maps into a new class objects and provide a schema for them too, but that is something I’d like to avoid.
Currently MOXy does not allow you to split the representation of a single instance into multiple locations within a JSON (or XML) tree. Please enter an enhancement request for the type of support you would like to see:
Below I’ll demonstrate how to map portions of your JSON message.
PARTIAL ANSWER #1
Below I’ll describe how to map your model to the following JSON message:
oxm.xml
PARTIAL ANSWER #2
Now I’ll describe how to map your model to the following JSON message:
oxm.xml
DEMO CODE
The same demo code can be used with both partial solutions:
DOMAIN MODEL
Below is the domain model that was used for both partial solutions:
PersonCollectionResponse
Person
Address
jaxb.properties
To specify MOXy as your JAXB provider you need to include a file called
jaxb.propertiesin the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html.