views:

49

answers:

1

Hi everyone, I have a java object like:

public class Person {
    private String firstName = "Harry";
    private String lastName = "Hacker";
    private int age = 30;
}

which I would like to marshal into the following xml:

<attribute xsi:type="someType" name="Person">
  <attribute xsi:type="CustomStringType" name="firstName">
    <value>Harry</value>
  </attribute>
  <attribute xsi:type="CustomStringType" name="lastName">
    <value>Hacker</value>
  </attribute> 
  <attribute xsi:type="CustomIntType" name="age">
    <value>30</value>
  </attribute>
</attribute>

so what I want to do, I want all objects in the Person (and the person itself) to be of xml-element "attribute" and to have this xml-element with an attribute "name" which represents the name of the field (lets assume Person is used as a field in class not shown here). Additionally I want to marshal the "primitive types" to have the "value" element with the appropriate value. Can this be done using JaxB? If yes how? What other solutions do you see when the requirement is that it has to be easy (i.e. just add some annotations to the new field) to add new "attributes" (i.e. fields (e.g. an address of the person) to the xml/class structure?

+1  A: 

Have you checked out implementing your own custom XmlAdapter, and anotate your Person type with @XmlJavaTypeAdapter anotation?

It allows you to define you own customized serialization strategy.

Tomas Narros
I thought about that, but that would require me to write an Adapter for each custom class within Person which wouldn't help the requirement for "easy" adding of new properties
Korgen
You cannot annotate your model directly to get the desired output. You will need to use something like XmlAdapter. The adapted object could leverage Java reflection APIs to make it easier to add new properties.
Blaise Doughan