0

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?

Killua Zoldyck
  • 25
  • 1
  • 1
  • 6

1 Answers1

2

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.

Ilya Novoseltsev
  • 1,803
  • 13
  • 19