避免在MOXy(JAXB+JSON)中创建对象包装类型/值

6

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

我希望ObjectElement和StringElement在进行序列化时可以被处理成相同的方式,但是当字段被定义为Object类型时,MOXy会创建一个包装对象。

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”属性的对象包装器?
1个回答

1
你可以使用注解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,并结合使用了type属性。
现在声明的类如下:
public class ObjectElement {
  @XmlElement(type = String.class)
  public Object testVar = "testValue";
}

你有其他的解决方案吗?我希望它也可以在不创建属性的情况下与XML一起使用,但值应该是<testVar>testValue</testVar>的文本内容。 - Toilal
是的,这是可能的。请查看我的更新答案以及在GitHub上的示例代码。 - Andreas Aumayr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接