我有以下类(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/