java - JAXB 未根据注释生成 XML (JDK 1.7)

标签 java xml jaxb

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;

    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;



    public class JavaToXMLDemo {
      public static void main(String[] args) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Employee.class);

    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Employee object = new Employee();
    object.setCode("CA");
    object.setName("Cath");
    object.setSalary(300);
    object.setProperties(new PropertiesMap());
    m.marshal(object, System.out);

  }
}

@XmlRootElement(name="Employee")
@XmlAccessorType(XmlAccessType.FIELD)
class Employee {
  private String code;

  @XmlElement(name = "Name")
  private String name;

  private int salary;

  @XmlElement(name = "Properties")
  protected PropertiesMap params;

  public String getCode() {
    return code;
  }

  public void setCode(String code) {
    this.code = code;
  }

  public PropertiesMap getProperties() {
      return params;
  }

  public void setProperties(PropertiesMap value) {
      this.params = value;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getSalary() {
    return salary;
  }

  public void setSalary(int population) {
    this.salary = population;
  }
}


  @XmlRootElement(name="Properties")
  class PropertiesMap<K,V> extends HashMap<K,V>
  {

  }

上面的代码使用 JDK 1.6 生成以下 XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee>
    <code>CA</code>
    <Name>Cath</Name>
    <salary>300</salary>
    <Properties/>
</Employee>  

这在 JDK 1.7 上

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee>
    <code>CA</code>
    <Name>Cath</Name>
    <salary>300</salary>
    <params/>
</Employee>  

为什么 Marshaller 的行为有所不同?

最佳答案

对于属性映射,您应该使用 @XmlElementWrapper 而不是 @XmlElement

参见http://blog.bdoughan.com/2013/03/jaxb-and-javautilmap.html用例#2。

关于java - JAXB 未根据注释生成 XML (JDK 1.7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25933481/

相关文章:

java - 从 JavaFX 应用程序写入/读取嵌套的 ObservableList

java - 如何将字节数组存储为磁盘上的图像文件?

Java Bean @Autowired 错误

php - 读取外部 XML 文件

javascript - 如何在JSP客户端页面上显示100K基于XML的DOM数据?

jaxb - 如何提高 JAXB 性能?

java - Hibernate 对象热切加载延迟集合

java - DBCP 关闭所有打开的连接

java - 为什么 Eclipse 不能导出类​​路径中包含的 Maven 库?

java - JAXB 基于子元素值解码子类