我有 2 个实体:
@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;
}
我可以使用一些魔法来获取 @XmlElement 的国家/地区名称作为简单的字符串,而不用 @Xml-annotations 包装国家/地区实体吗?
最佳答案
您可以为您的Country
类型创建自定义@XmlJavaTypeAdapter
:
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;
}
}
然后您只需像这样注释您的国家/地区字段:
@Entity
@XmlRootElement
public class test {
@Getter
@Setter
@XmlElement(name = "country")
@XmlJavaTypeAdapter(CountryXmlAdapter.class)
private Country country
}
或者,如果您只关心单向编码,请尝试在 test
类中创建一个方法 getCountryName()
并对其进行注释它与@XmlElement
。
关于java - @XmlElement - 从未使用 @xml-annotation 映射的对象获取字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47410760/