java - @XmlElement - 从未使用 @xml-annotation 映射的对象获取字符串值

标签 java xml xml-binding

我有 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/

相关文章:

Java构造函数问题

java - 如何将一个类中的文本字段文本显示到另一个类的标签中

python - ElementTree的iterparse() XML解析错误

c# - 使用 C# 反序列化 XML HTTP 响应

java - 在 JiBX 中绑定(bind)额外信息

java - 该 xml 文件的 jaxb 注释应该是什么?

java - 具有继承的 Jaxb POJO 生成

java - 使 Jtextarea 能够被复制

java - 无法编译已实现接口(interface)的抽象类

python - 使用 minidom.toprettyxml 时的空行