JAXB 编组和解组映射 to/from <key>值</key>

JAXB Marshal and Unmarshal Map to/from <key>value</key>

我正在尝试编组和取消编组 Map to/from 值对。我可以成功编组该对象,但是,我无法从 xml 中解组它。 unmarshal 的结果是 key 存在于 Map 中,但是它的值为 null。

这是我要编组和解组的模型:

import java.util.Map;
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.adapters.XmlJavaTypeAdapter;

@XmlRootElement(name="TestModel")
@XmlAccessorType(XmlAccessType.FIELD)
public class TestModel {

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

    @XmlJavaTypeAdapter(MapAdapter.class)
    private Map<String, String> metadata;

    public String getName() {
        return name;
    }

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

    public Map<String, String> getMetadata() {
        return metadata;
    }

    public void setMetadata(Map<String, String> metadata) {
        this.metadata = metadata;
    }
}

我为编组和解组创建了一个映射适配器,如下所示:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.namespace.QName;
import org.w3c.dom.Element;

public class MapAdapter extends XmlAdapter<MapWrapper, Map<String, String>> {

@Override
public MapWrapper marshal(Map<String, String> m) throws Exception {
    MapWrapper wrapper = new MapWrapper();
    List<JAXBElement<String>> elements = new ArrayList<JAXBElement<String>>();
    if (m != null && !m.isEmpty()) {
        for (Entry<String, String> property : m.entrySet()) {
            elements.add(new JAXBElement<String>(new QName(property.getKey()), 
                    String.class, property.getValue().toString()));
        }
    }
    wrapper.elements = elements;
    return wrapper;
}

@Override
public Map<String, String> unmarshal(MapWrapper v) throws Exception {
    Map<String, String> map = new HashMap<String, String>();
    if (v != null && v.elements != null && !v.elements.isEmpty()) {
        for (Object object : v.elements) {
            Element element = (Element) object;
            map.put(element.getNodeName(), element.getNodeValue());
        }
    }
    return map;
}

}

class MapWrapper {

    @XmlAnyElement(lax=true)
    protected List<JAXBElement<String>> elements;
}

下面class可以测试上面模型的编组和解组:

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class TestEntry {

public static void main(String[] args) throws JAXBException {
    testMarshal();
    testUnmarshal();
}

public static void testMarshal() throws JAXBException {

    Map<String, String> metadata = new HashMap<String, String>();
    metadata.put("category", "test");
    metadata.put("creation", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
    TestModel model = new TestModel();
    model.setMetadata(metadata);
    model.setName("TESTMODEL");

    marshal(model, System.out);
}

public static void testUnmarshal() throws JAXBException {

    String model = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>"
            + "<TestModel>"
            +   "<Name>TESTMODEL</Name>"
            +   "<metadata>"
            +       "<category>test</category>"
            +       "<creation>2015-09-29</creation>"
            +   "</metadata>"
            + "</TestModel>";

    TestModel result = unmarshal(new ByteArrayInputStream(model.getBytes()), TestModel.class);
    System.out.println("name=" + result.getName());
    for (String key : result.getMetadata().keySet()) {
        System.out.println(key + ", " + result.getMetadata().get(key));
    }
}

public static <T> void marshal(T cls, OutputStream os) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(cls.getClass());
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(cls, os);
}

@SuppressWarnings("unchecked")
public static <T> T unmarshal(InputStream is, Class<T> cls)
        throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(cls);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    return (T) unmarshaller.unmarshal(is);
}
}

调用'public Map unmarshal(MapWrapper v) throws Exception'.

时,地图似乎只包含具有'null'值的键

而且我也找到了关于这个问题“JAXB: how to marshall map into <key>value</key>”的类似问题,但是,它并没有解决解组问题?

一个非常小修正:

map.put(element.getNodeName(), element.getTextContent());