NumberFour
NumberFour

Reputation: 3621

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>[email protected]</Value>
  </Entry>
 </Entries>
</Root>

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

{ "Age": 35, "Email": "[email protected]" }

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?

Upvotes: 2

Views: 364

Answers (1)

bdoughan
bdoughan

Reputation: 149017

Instead of:

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

Do:

public static class JsonXmlAdapter extends XmlAdapter<XmlJsonEntries, JsonObject>

And then have XmlJsonEntries have a mapped property that is of type List<XmlJsonEntry>.

Upvotes: 2

Related Questions