0

I have a problem when using an array of interfaces in a class that I want to marshal/unmarshal to/from JSON.

Here's some example code:

import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;

import org.eclipse.persistence.jaxb.JAXBContext;

public class TestMain {

    public static interface Test {
        String getVal();
    }

    public static final class TestImpl implements Test {
        @Override
        @XmlValue
        public String getVal() {
            return "HELLO";
        }
    }

    @XmlRootElement(name = "TestJSON")
    @XmlAccessorType(XmlAccessType.NONE)
    public static final class TestJSON {

        @XmlElement(name = "Selection", type = TestImpl.class)
        public Test[] getTestInt() {
            return new TestImpl[] {
                new TestImpl(), new TestImpl()
            };
        }

    }

    public static void main(String[] args) throws Exception {
        Marshaller m = JAXBContext.newInstance(TestJSON.class).createMarshaller(); 
        m.setProperty("eclipselink.media-type", "application/json");
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        m.marshal(new TestJSON(), System.out);
    }

}

Here's the output I get:

{
   "TestJSON" : {
      "Selection" : [ "test.TestMain$TestImpl@49fc609f", "test.TestMain$TestImpl@cd2dae5" ]
   }
}

And here's what I would expect and which I can get if I use a List<Test> instead of an array:

{
   "TestJSON" : {
      "Selection" : [ "HELLO", "HELLO" ]
   }
}

Is this something MOXy can't handle, or am I missing something?

I using version 2.5.1

muhmud
  • 4,474
  • 2
  • 15
  • 22

1 Answers1

0

You're declaring the @XmlValue annotation on the implementation level and you're actually returning an array of TestImpl[], but the getTestInt() method is casting the array as Test[], therefore the annotation is not visible at that level. I think if you put the annotation on the interface instead, it'll solve your problem.

public static interface Test {
    @XmlValue
    String getVal();
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • It should be fine as I'm using `type` in my `XmlElement` annotation. Also, I don't want to have to put any annotations in my interface. – muhmud Jun 15 '14 at 20:30
  • Don't know enough about moxy to comment further. But if you're looking for a workaround, you should be able to override `toString` on `TestImpl`. – shmosel Jun 15 '14 at 21:02