避免在 MOXy (JAXB+JSON) 中创建对象包装器 type/value

Avoid creation of object wrapper type/value in MOXy (JAXB+JSON)

我正在使用 MOXy 2.6 (JAXB+JSON)。

我希望 ObjectElement 和 StringElement 以相同的方式编组,但 MOXy 在字段类型为 Object 时创建包装器对象。

ObjectElement.java

public class ObjectElement {
    public Object testVar = "testValue";
}

StringElement.java

public class StringElement {
    public String testVar = "testValue";
}

Demo.java

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.oxm.MediaType;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContextFactory.createContext(new Class[] { ObjectElement.class, StringElement.class }, null);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);

        System.out.println("ObjectElement:");
        ObjectElement objectElement = new ObjectElement();
        marshaller.marshal(objectElement, System.out);
        System.out.println();

        System.out.println("StringElement:");
        StringElement stringElement = new StringElement();
        marshaller.marshal(stringElement, System.out);
        System.out.println();
    }

}

启动时Demo.java,输出如下...

ObjectElement:
{"testVar":{"type":"string","value":"testValue"}}
StringElement:
{"testVar":"testValue"}

如何配置 MOXy/JaxB 使 ObjectElement 呈现为 StringElement 对象?如何避免创建具有 "type""value" 属性的对象包装器?

您可以使用注解javax.xml.bind.annotation.XmlAttribute。这会将 ObjectElement 和 StringElement 呈现为相同的输出。

参见以下示例:

import javax.xml.bind.annotation.XmlAttribute;

public class ObjectElement {
    @XmlAttribute
    public Object testVar = "testValue";
}

我使用以下 test class 来验证正确的行为。

问题更新后编辑:

是的,这是可能的。我没有像以前那样使用 XmlAttribute,而是将 javax.xml.bind.annotation.XmlElement 与类型属性结合使用。

class 现在声明为:

public class ObjectElement {
  @XmlElement(type = String.class)
  public Object testVar = "testValue";
}