简体   繁体   中英

JAXB not generating XML as per the Annotations (JDK 1.7)

    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>
  {

  }

The above code generates the below XML with JDK 1.6

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

and this on JDK 1.7

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

Why does the Marshaller behave differently?

You should use @XmlElementWrapper instead of @XmlElement for your Properties map.

See http://blog.bdoughan.com/2013/03/jaxb-and-javautilmap.html use case #2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM