java - JAXB 映射 将复杂对象映射到 JSON

标签 java json jaxb moxy

我在将我的复杂对象序列化为 JSON 时遇到问题,该对象包含带有另一个复杂对象的 Map。我正在使用 JAXB 和 MOXy。这是我的类(class): 我要序列化/反序列化的根类:

@XmlRootElement
@XmlSeeAlso(ComplexBean.class)
@XmlAccessorType(XmlAccessType.FIELD)
public class MapBean implements Serializable {

    @XmlJavaTypeAdapter(MapAdapter.class)
    @XmlElement
    private Map<String, ComplexBean> complexBeans;

我的 ComplexBean 类(省略了 getter/setter):

public class ComplexBean implements Serializable {
    private String name;
    private String surName;
    private double weight;

MapAdapter 类:

public class MapAdapter extends XmlAdapter<Element, Map<String, ComplexBean>> {

private DocumentBuilder documentBuilder;

public MapAdapter() throws Exception {
    documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
}

public Element marshal(Map<String, ComplexBean> map) throws Exception {
    Document document = documentBuilder.newDocument();
    Element rootElement = document.createElement("complexBeans");
    document.appendChild(rootElement);
    for(Map.Entry<String, ComplexBean> entry : map.entrySet()) {
        Element childElement = document.createElement(entry.getKey());
        ComplexBean complexBean = entry.getValue();

        Attr nameAttribute = document.createAttribute("name");
        nameAttribute.setValue(complexBean.getName());
        childElement.setAttributeNode(nameAttribute);

        Attr surNameAttribute = document.createAttribute("surName");
        surNameAttribute.setValue(complexBean.getSurName());
        childElement.setAttributeNode(surNameAttribute);

        Attr weightAttribute = document.createAttribute("weight");
        weightAttribute.setValue(String.valueOf(complexBean.getWeight()));
        childElement.setAttributeNode(weightAttribute);

        rootElement.appendChild(childElement);
    }
    return rootElement;
}

public Map<String, ComplexBean> unmarshal(Element element) throws Exception {
    System.out.println("In unmarshaller");
    Map<String, ComplexBean> complexBeans = new HashMap<String, ComplexBean>();
    return null;
}
}

还有我的主要方法:

public static void main(String[] args) throws Exception {
    Map<String, Object> jaxbProperties = new HashMap<String, Object>();
    jaxbProperties.put(JAXBContextProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
    jaxbProperties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
    javax.xml.bind.JAXBContext jc = JAXBContext.newInstance(new Class[] {MapBean.class}, jaxbProperties);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    MapBean mapBean = getMapBean();

    Writer writer = new StringWriter();
    marshaller.marshal(mapBean, writer);
    String json = writer.toString();
    System.out.println("Output JSON: ");
    System.out.println(json);

    StreamSource streamSource = new StreamSource(json);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    MapBean unmarshalledMapBean = unmarshaller.unmarshal(streamSource, MapBean.class).getValue();
    System.out.println(unmarshalledMapBean);
}

所以,当我运行我的 main 方法时,marshaller 返回这样的 json:

{
   "complexBeans" : {
      "first" : {
         "name" : "cbName1",
         "surName" : "cbSurName1",
         "weight" : "50.5"
      },
      "second" : {
         "name" : "cbName2",
         "surName" : "cbSurName2",
         "weight" : "10.5"
      }
   }
}

但是 umarshaller 没有调用 MapAdapter 类中的 unmarshall 方法,并且失败并出现异常:

Caused by: Exception [EclipseLink-25004] (Eclipse Persistence Services - 2.6.1.v20150916-55dc7c3): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: An error occurred unmarshalling the document
Internal Exception: java.net.MalformedURLException: no protocol: {
   "complexBeans" : {
      "first" : {
         "name" : "cbName1",
         "surName" : "cbSurName1",
         "weight" : "50.5"
      },
      "second" : {
         "name" : "cbName2",
         "surName" : "cbSurName2",
         "weight" : "10.5"
      }
   }
}
    at  org.eclipse.persistence.exceptions.XMLMarshalException.unmarshalException(XMLMarshalException.java:120)
    at org.eclipse.persistence.internal.oxm.record.json.JsonStructureReader.parse(JsonStructureReader.java:156)
    at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:863)
    at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:710)
    at org.eclipse.persistence.internal.oxm.XMLUnmarshaller.unmarshal(XMLUnmarshaller.java:643)
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:339)
    ... 1 more
    at java.net.URL.<init>(URL.java:586)
    at java.net.URL.<init>(URL.java:483)
    at java.net.URL.<init>(URL.java:432)
    at   org.eclipse.persistence.internal.oxm.record.json.JsonStructureReader.parse(JsonStructureReader.java:127)
    at org.eclipse.persistence.internal.oxm.record.json.JsonStructureReader.parse(JsonStructureReader.java:154)
    ... 5 more

所以,请帮助我将 json 解码为 MapBean 对象。我的错误是什么?

最佳答案

您的 StreamSource 调用在 main 方法中是错误的。您直接将 json 字符串传递给 StreamSource 构造函数。

这是你目前拥有的——

StreamSource streamSource = new StreamSource(String json);

根据 StreamSource specification,您应该有如下内容

StreamSource streamSource = new StreamSource("file location/URL");

或者

StreamSource streamSource = new StreamSource(File);

关于java - JAXB 映射 将复杂对象映射到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38942547/

相关文章:

java - 使用 Gson 泛化字段名称

javascript - REST 的 JSON 中 snake_case 相对于 camelCase 的优势

javascript - 从嵌套的 json 对象中获取最小值

jaxb - xs :int unmarshalled to null for decimal values

java - 为什么我的 Android 程序中会出现 PatternSyntaxException?

java - 在这种情况下如何删除最后一个括号

java - Bcrypt 自定义密码配置

java - 如何解密mysql中的消息?

Java/JAXB : Unmarshall XML attributes to specific Java object attributes

java - 将子 XML 元素反序列化为 XML 字符串