java - 使用 MOXy 将 JsonObject 属性映射到 XML

标签 java xml json marshalling moxy

我有以下类(class)

@XmlRootElement(name = "Root")
class MyClass {

    @XmlElement(name = "Entries")
    JsonObject getProperty() { ... }
}

我希望在编码后得到以下 XML 输出:

<Root>
  <Entries>
  <Entry>
    <Name>Age</Name>
    <Value>35</Value>
  </Entry>
  <Entry>
    <Name>Email</Name>
    <Value><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="483c2d3b3c082f25292124662b2725" rel="noreferrer noopener nofollow">[email protected]</a></Value>
  </Entry>
 </Entries>
</Root>

前提是从getProperty()返回的JSON是:

{ "Age": 35, "Email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d19081e192d0a000c0401430e0200" rel="noreferrer noopener nofollow">[email protected]</a>" }

我试图创建一个辅助类 XmlJsonEntry

@XmlAccessType(XmlAccessType.FIELD)
@XmlRootElement(name = "Entry")
class XmlJsonEntry {
   @XmlElement
   public String Name;
   @XmlElement
   public String Value;
}

并扩展XmlAdapter如下:

public static class JsonXmlAdapter extends XmlAdapter<XmlJsonEntry[], JsonObject>
{

    @Override
    public XmlJsonEntry[] marshal(JsonObject v) throws Exception 
    {
        List<XmlJsonEntry> entries = new ArrayList<XmlJsonEntry>();
        for (Entry<String,JsonElement> e : v.entrySet())
        {
            entries.add(new XmlJsonEntry(e.getKey(),e.getValue().toString()));
        }
        return entries.toArray(new XmlJsonEntry[entries.size()]);
    }

    @Override
    public JsonObject unmarshal(XmlJsonEntry[] v) throws Exception 
    { throw new Exception("Unmarshall not supported."); }

}

但这在编码期间引发了异常:

Trying to get value for instance variable [name] of type [java.lang.String] from the object [[Lmy.app.$XmlJsonEntry;]. The specified object is not an instance of the class or interface declaring the underlying field`

我该如何让它发挥作用?也许有一些更简单的方法来实现这一目标吗?

最佳答案

而不是:

public static class JsonXmlAdapter extends XmlAdapter<XmlJsonEntry[], JsonObject>

做:

public static class JsonXmlAdapter extends XmlAdapter<XmlJsonEntries, JsonObject>

然后有XmlJsonEntries有一个类型为 List<XmlJsonEntry> 的映射属性.

关于java - 使用 MOXy 将 JsonObject 属性映射到 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27840110/

相关文章:

java - 用于 Java 的现代 Flickr API

java - 从 Bitmap 类创建 .bmp 图像文件

java - 如何配置 jaxb setter?

javascript - JSON 对象属性转换为 JSON 对象名称

Java:动态变量响应为 JSON

javascript - 无法访问 JSON 对象,因为 "wrapper"

Java Swing 文本编辑器抛出 NullPointerException

java - 无法将 Gson JsonObject 转换为 POJO 类

xml - 为什么这个 Powershell 函数有时返回一个列表而其他时候返回一个 XmlElement?

java - 在 Java 中读取 XML 元素列表