I have 2 entities:
@Entity
@XmlRootElement
public class test {
@Getter
@Setter
@XmlElement(HERE I WANT THE NAME OF THE COUNTRY)
private Country country
}
@Entity
public class Country {
@Getter
@Setter
private String name;
@Getter
@Setter
private String capital;
}
Is there some magic I can use to get the name of the country for the @XmlElement as a simple String without wrap the country entity with @Xml-annotations?
You can create a custom @XmlJavaTypeAdapter
for your Country
type:
public static class CountryXmlAdapter extends XmlAdapter<String, Country> {
@Override
public Country unmarshal(String v) throws Exception {
Country c = new Country();
c.setName(v);
return c;
}
@Override
public String marshal(Country v) throws Exception {
return v != null ? v.getName() : null;
}
}
Then you simply annotate your country field like that:
@Entity
@XmlRootElement
public class test {
@Getter
@Setter
@XmlElement(name = "country")
@XmlJavaTypeAdapter(CountryXmlAdapter.class)
private Country country
}
Or, if you care about one-way marshalling only, try creating a method getCountryName()
in your test
class and annotate it with @XmlElement
.