JAXB: change XML element name from Java code?

To set the name of the XML element, I use annotations like this:

@XmlElement(name = "customer_id") public String getId(){} 

I need to communicate with two different web services. One of them produces an id element named customer_id , and the other an identification element, which will be called id . I solved the problem by creating a second Customer class with the same attributes. The only difference is that it uses the following annotation

 @XmlElement(name = "id") public String getId(){} 

and has a copy constructor that copies all attributes from Customer1 to Customer2 . When I talk to the first web service, I send the Customer1 object, and the other web service receives the Customer2 object.

Is it possible to use only one Customer object, but rename the id attribute to everything that the web service expects?

+6
source share
1 answer

Note. I am EclipseLink JAXB (MOXy) and a member of the JAXB 2 Expert Group (JSR-222) .

You can use the external display document extension in MOXy JAXB to apply the second mapping to your object model. This mapping document can be used to modify the metadata provided through annotations, or completely replace it.

Detailed example

In the example below, one object model maps to the results of the Google and Yahoo Weather APIs:

+5
source

Source: https://habr.com/ru/post/900847/


All Articles