Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Using MOXy, how would you map a JSON property address.city into a flat field city on a Customer class, and what properties make the JSON output omit the root element?

With EclipseLink MOXy as the JAXB runtime, we annotate the flat field with @XmlPath("address/city/text()"), which maps it to the city inside a nested address object without needing an Address class. Setting the marshaller property MarshallerProperties.MEDIA_TYPE to application/json makes MOXy write JSON, and MarshallerProperties.JSON_INCLUDE_ROOT set to false leaves out the root wrapper object. The same mappings drive XML output, so we test both forms, and @XmlPath is MOXy-specific, which ties the code to MOXy.

Why this question is asked

MOXy is EclipseLink's implementation of Jakarta XML Binding, and it adds two features the reference implementation lacks: path-based mappings and JSON output from the same annotations. Teams that already have JAXB models for XML sometimes use it to offer JSON without a second mapping. Interviewers ask this coding question to check that we know the MOXy-specific annotations and properties, and that we understand the cost of depending on them. In this answer, we will set up MOXy, map the nested city with @XmlPath, produce JSON with and without the root, read it back, and look at what the same mapping does in XML and what it costs in portability.

1A Quick Recap: MOXy as a JAXB Runtime

Jakarta XML Binding is an API with several implementations, called runtimes. Our code uses the standard JAXBContext, Marshaller and Unmarshaller; the runtime decides how the work is done. To use MOXy, we add its dependency and either create contexts through MOXy's factory directly or tell JAXB to use MOXy with a jaxb.properties file in the package of the model classes. The MOXy 4.x line targets jakarta.xml.bind (check your version).

XML
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.moxy</artifactId>
<version>4.0.x</version>
</dependency>
// Option 1: create the context with MOXy's factory directly
JAXBContext ctx = org.eclipse.persistence.jaxb.JAXBContextFactory
.createContext(new Class<?>[] {Customer.class}, null);
// Option 2: src/main/resources/com/acme/customers/jaxb.properties
// jakarta.xml.bind.JAXBContextFactory=org.eclipse.persistence.jaxb.JAXBContextFactory
JAXBContext ctx2 = JAXBContext.newInstance(Customer.class); // now a MOXy context

The direct factory call is more explicit and survives refactoring, because a jaxb.properties file in the wrong package is silently ignored and the reference runtime is used instead. A quick check is ctx.getClass().getName(), which should name an org.eclipse.persistence class.

2Mapping a Nested Path to a Flat Field

The JSON has a nested object, address with a city inside it, but our Customer class has just a flat city field. Standard JAXB would require an Address class to hold the nesting. MOXy's @XmlPath annotation takes an XPath, a path expression through the document, and maps the field to that location directly.

Java
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement(name = "customer")
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
@XmlElement private String id;
@XmlElement private String name;
@XmlPath("address/city/text()")
private String city;
@XmlPath("address/postcode/text()")
private String postcode;
Customer() {}
public Customer(String id, String name, String city, String postcode) {
this.id = id; this.name = name; this.city = city; this.postcode = postcode;
}
public String getCity() { return city; }
public String getPostcode() { return postcode; }
}

The path reads from the customer element: go into address, then into city, and take its text(), the text content. Both city and postcode share the address step, so MOXy writes them into one address object, not two. Without text(), the path would refer to the element itself, which is used for nested object mappings; for a simple value we want its text.

3Producing JSON, With and Without the Root

JSON output is controlled by marshaller properties from org.eclipse.persistence.jaxb.MarshallerProperties. MEDIA_TYPE set to application/json switches the output format. By default MOXy wraps the object in a property named after the root element, because XML always has one root; JSON_INCLUDE_ROOT set to false removes that wrapper, which is what most JSON APIs expect.

Java
Customer c = new Customer("C-9", "Ada", "Leeds", "LS1 4AP");
Marshaller m = ctx.createMarshaller();
m.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
m.marshal(c, System.out);
// {"customer":{"id":"C-9","name":"Ada","address":{"city":"Leeds","postcode":"LS1 4AP"}}}
m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
m.marshal(c, System.out);
// {"id":"C-9","name":"Ada","address":{"city":"Leeds","postcode":"LS1 4AP"}}
Marshaller settings and the output they give
MEDIA_TYPEJSON_INCLUDE_ROOTOutput
application/xml (default)not used<customer><id>C-9</id>...<address><city>Leeds</city>...
application/jsontrue (default){"customer":{"id":"C-9",...,"address":{"city":"Leeds"}}}
application/jsonfalse{"id":"C-9",...,"address":{"city":"Leeds"}}

Reading JSON back uses the matching UnmarshallerProperties. With the root excluded, the JSON no longer says which class it is, so we pass the class explicitly, just as with an XML element that has no root declaration, and get a JAXBElement back.

4Reading the JSON Back

Unmarshalling follows the same settings. The nested address.city value is read straight into the flat city field through the same @XmlPath.

Java
Unmarshaller u = ctx.createUnmarshaller();
u.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
u.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
String json = "{\"id\":\"C-9\",\"name\":\"Ada\",\"address\":{\"city\":\"Leeds\"}}";
Customer back = u.unmarshal(new StreamSource(new StringReader(json)), Customer.class).getValue();
back.getCity(); // "Leeds"
back.getPostcode(); // null: not present in the JSON

5The Same Mapping in XML, and Why We Test Both

The mappings are XML mappings first; JSON is a second rendering of them. Marshalling the same object with the default media type gives XML with an address element containing city and postcode. That is convenient, but the two formats differ in ways that can surprise us. Attributes have no JSON equivalent, so MOXy writes them as ordinary properties, optionally with a prefix set by JSON_ATTRIBUTE_PREFIX. A list with one item may need configuration to stay a JSON array. Numbers and booleans are written as JSON types only when the Java type is numeric or boolean. And namespaces need extra settings in JSON.

So when one model serves both formats, both outputs need tests: one that marshals a sample to XML and validates it against the schema if there is one, and one that marshals to JSON and compares it with an expected document. Otherwise a change made for one format quietly alters the other.

Java
@Test
void sameModelBothFormats() throws Exception {
assertThat(toXml(sample())).isEqualTo(
"<customer><id>C-9</id><name>Ada</name><address><city>Leeds</city><postcode>LS1 4AP</postcode></address></customer>");
JSONAssert.assertEquals(
"{\"id\":\"C-9\",\"name\":\"Ada\",\"address\":{\"city\":\"Leeds\",\"postcode\":\"LS1 4AP\"}}",
toJson(sample()), true);
}

6The Cost: Tying the Code to MOXy

@XmlPath, MarshallerProperties and UnmarshallerProperties live in org.eclipse.persistence packages, not in jakarta.xml.bind. With the reference runtime, @XmlPath is simply ignored, so the city field would be written as a plain <city> element, and the JSON properties would be rejected. The model now only works correctly on MOXy.

That is a reasonable trade when the convenience is large and the code is contained, for example in one integration module whose job is to translate a partner's nested format. For general-purpose JSON APIs, most Spring applications use Jackson instead, which has richer JSON features and is the default in Spring Boot; Jackson can also flatten nested values with @JsonUnwrapped or a custom mapping. Choosing MOXy for JSON makes most sense when the same JAXB model really must produce both XML and JSON.

7Follow-up questions

Can @XmlPath map an attribute?

Yes, with @ in the path, for example @XmlPath("address/@type") maps a field to the type attribute of the address element. In JSON, that attribute becomes a property of the address object.

How do I make MOXy the JSON provider in a JAX-RS application?

MOXy provides a JAX-RS provider class, and Jersey can use MOXy for JSON through its own module. In Spring MVC, Jackson is the default message converter, and switching to MOXy needs a custom converter, which is rarely worth it.

Is JSON_INCLUDE_ROOT needed when reading too?

Yes. If the JSON has no root wrapper, the unmarshaller must be told with UnmarshallerProperties.JSON_INCLUDE_ROOT set to false, and the class must be given explicitly with unmarshal(source, Customer.class).

8Conclusion

In this answer, we used MOXy as the JAXB runtime and mapped a nested address.city value to a flat field with @XmlPath("address/city/text()"). MarshallerProperties.MEDIA_TYPE set to application/json produced JSON, JSON_INCLUDE_ROOT set to false removed the root wrapper, and the matching UnmarshallerProperties read it back with the class given explicitly. We saw that the same mappings drive XML output, so both forms need tests, and that @XmlPath and the JSON properties tie the model to MOXy.

What to say in the interviewAbout 80 seconds aloud

Open with

First I make sure MOXy is actually the runtime, either by creating the context with org.eclipse.persistence.jaxb.JAXBContextFactory or with a jaxb.properties file in the model's package, and I check the context's class name, because a misplaced properties file silently falls back to the reference runtime.

Then, if they want more

For the nested city, I put @XmlPath with address/city/text() on the flat city field. That XPath says: inside address, take the text of city, so I don't need an Address class, and other fields with the same address step end up in the same nested object. To produce JSON, I set MarshallerProperties.MEDIA_TYPE to application/json on the marshaller.

By default MOXy wraps the object in a property named after the root element, so I set MarshallerProperties.JSON_INCLUDE_ROOT to false to get a plain object. To read it back, I set the same two properties through UnmarshallerProperties and unmarshal with the class given explicitly, because without the root the JSON does not say what it is.

The same mappings also drive XML, where the city appears inside an address element, so I'd test both formats. And I'd point out that @XmlPath and those properties are MOXy-specific, so the model only works correctly on MOXy; I'd keep that in an integration module and use Jackson for ordinary JSON APIs.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Using MOXy, how would you map a JSON property address.city into a flat field city on a...": https://scrivio-interview-library.netlify.app/java/jaxb/9915bb8aff/