0

My Goal is to use this XML

<data>
  <description lang="de">Deutscher Text</description>
  <description lang="en">english text</description>
</data>

into this type:

@XmlAccessorType( XmlAccessType.FIELD )
@XmlRootElement
@XmlSeeAlso( {
        Description.class
} )
public class Data
{
    @XmlElement( name = "description" )
    @XmlJavaTypeAdapter( LanguageAdapter.class )
    Map<String, String> descriptions = new HashMap<>();
}

using the following XMLAdapter and intermediate type:

@XmlAccessorType( XmlAccessType.FIELD )
@XmlRootElement
public class Description
{
    @XmlAttribute
    String lang;

    @XmlValue
    String value;

    public Description( String lang, String value )
    {
        this.lang = lang;
        this.value = value;
    }

    public Description()
    {}
}


// import static java.util.Arrays.stream;
// import static java.util.stream.Collectors.toMap;
public class LanguageAdapter extends XmlAdapter<Description[], Map<String, String>>
{

    @Override
    public Map<String, String> unmarshal( Description[] v ) throws Exception
    {
        return stream( v )
         .collect( toMap( Description::getLang, Description::getValue ) );
    }

    @Override
    public Description[] marshal( Map<String, String> v ) throws Exception
    {
        return v.entrySet().stream()
                .map( e -> new Description( e.getKey(), e.getValue() ) )
                .toArray( Description[]::new );
    }

}

unfortunately, the map is not filled and marshalling the data structure yields this xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data>
    <description>
        <item lang="de">deutsch</item>
        <item lang="en">english</item>
    </description>
</data>

Is there a way to solve this?

Max Fichtelmann
  • 3,366
  • 1
  • 22
  • 27
  • Please have a look at https://stackoverflow.com/questions/51805298/deserialize-xml-to-pojo-using-jackson-xml-mapper/51805570#51805570 – S.K. Aug 14 '18 at 14:17
  • thank you, but I am looking for a solution for JAXB. I will see, if I can use it. – Max Fichtelmann Aug 14 '18 at 16:27

0 Answers0