在我想要编组/解组JSON的类中使用接口数组时遇到问题。
以下是一些示例代码:
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);
}
}
这是我得到的输出:
{
"TestJSON" : {
"Selection" : [ "test.TestMain$TestImpl@49fc609f", "test.TestMain$TestImpl@cd2dae5" ]
}
}
这就是我期望的,如果我使用List<Test>
代替数组,我可以得到什么:
{
"TestJSON" : {
"Selection" : [ "HELLO", "HELLO" ]
}
}
这是MOXy无法处理的事情,还是我错过了什么?
我使用的是2.5.1版本
答案 0 :(得分:0)
您在实现级别声明了@XmlValue
注释,并且您实际上返回了TestImpl[]
的数组,但getTestInt()
方法将数组转换为Test[]
因此,注释在该级别不可见。我想如果你把注释放在界面上,它就能解决你的问题。
public static interface Test {
@XmlValue
String getVal();
}