Routing Nested Objects with JAXB - The Detailed

I have a very simple problem here, but after using Google for over an hour, I still can't find a good solution and it starts to cost too much money.

In my application, I use REST as the API, mostly just with JSON as the payload type and Enunciate for the API documentation. As you probably know, enunciate will generate xsd schema from classes. So I'm in a situation like this that I need to set up all DTOs to handle Jackson / JSON with suitable annotations as well as JAXB annotation to make sure the generated schema is correct and can be parsed with XJC into the correct classes!

While this is not very difficult in most cases and works flawlessly, I have a simple but somehow special case in which it completely fails.

Assuming the following classes:

@JsonRootName(value = "location")
public class Location {
    
  private String label;
  
  @JsonUnwrapped
  private Address address;
  
  // constructors, getters, setters ommited..
}


//// new file

public class Address{
  
  private String city;
  private String street;
  private String postCode;
  
}
      

Run codeHide result


This works 100% with Jackson / JSON. The embedded address object will be expanded so that the JSON looks like this:

{
  "label":"blah",
  "street":"Exchange Road",
  "city":"Stacktown"
  "postCode":"1337"
}
      

Run codeHide result


It works back and forth with Jackson. JAXB, on the other hand, can parse (most of) Jackson's annotations, so generally you won't have problems using simple objects in both worlds. @JsonUnwrapped, although unfortunately not supported by JAXB and it's strange that (from my POV) a fairly simple usecase doesn't seem to be reflected in any JAXB annotation.

What is happening is that the generated schema contains an embedded Address object without any attributes / elements. Therefore, the XJC generated class will contain a reference to the Address object. And this ultimately results in erroneous JSON from the application which will use the schema to generate objects ...

Any ideas?

+3


source to share


1 answer


The JAXB specification (JSR-222) does not define a Jackson equivalent @JsonUnwrapped

. For a long time we have offered this functionality in the EclipseLink MOXy JAXB implementation via an extension @XmlPath

.

  @XmlPath(".")
  private Address address;

      

Additional Information



I wrote more about the MOXy extension @XmlPath

on my blog:

+1


source







All Articles