Question

My JAXB classes are as below

@XmlRootElement
class A
{
    @XmlElement(name = "bean")
    List<Bean> beans;
    . . .
}

@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
class Bean
{
    @XmlAttribute
    String name;
    @XmlValue
    String value;
    . . .
}

When i marshal data i get this

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a>
    <bean name="Name1">Value1</bean>
    <bean name="Name2">Value2</bean>
</a>

Can i achieve similar output using Map<String,String> instead of List<Bean>?

So far my attempts were like this

@XmlRootElement
class A
{
    @XmlJavaTypeAdapter(MyAdapter.class)
    Map<String, String> map;
    . . .
}

class BeanList
{
    @XmlElement(name = "bean")
    List<Bean> beans;
    . . .
}

class MyAdapter extends XmlAdapter<BeanList, Map<String, String>>
{
    @Override
    public BeanList marshal(Map<String, String> map) throws Exception
    {
     . . .
    }

    @Override
    public Map<String, String> unmarshal(BeanList list) throws Exception
    {
     . . .
    }
}

But this gives me output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a>
    <map>
        <bean name="Name4">Value4</bean>
        <bean name="Name3">Value3</bean>
    </map>
</a>

is there any way to avoid <map> tag...

Any help in this regard would be highly appreciated

Was it helpful?

Solution

Solved this by changing map to transient and adding private/default set + get methods to do the conversion to List<Bean> with annotation XmlElement

@XmlRootElement
class A
{
  @XmlTransient
  Map<String, String> map;

  //For JAXB use
  private void setBeans(List<Bean> beans)
  {
    //Populate map
  }

  //For JAXB use
  @XmlElement(name = "bean")
  private List<Bean> getBeans()
  {
    //Convert map to List<Bean>
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top