Mapping JsonObject property to XML with MOXy



I have the following class



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

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


I would like to have the following XML output after marshalling:



<Root>
<Entries>
<Entry>
<Name>Age</Name>
<Value>35</Value>
</Entry>
<Entry>
<Name>Email</Name>
<Value>test@gmail.com</Value>
</Entry>
</Entries>
</Root>


provided that the JSON returned from the getProperty() is:


{ "Age": 35, "Email": "test@gmail.com" }


I was trying to create a helper class XmlJsonEntry



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


and extend the XmlAdapter as follows:



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."); }

}


But this throws me an exception during Marshalling:



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`



How do I get this working? Is there perhaps some easier way to achieve this?


No comments:

Post a Comment