更新时间:2023-11-27 11:48:10
注意:我是 EclipseLink JAXB(MOXy) 领导和 JAXB 2(JSR-222) 专家组。
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
以下是在EclipseLink JAXB(MOXy)中使用JSON绑定支持此用例的方法。
Below is how you could support this use case using the JSON-binding in EclipseLink JAXB (MOXy).
Java模型(根)
下面是我将用于此示例的Java模型。
Below is the Java model that I will use for this example.
import java.util.*;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Root {
private List<String> channels = new ArrayList<String>();
@XmlElementWrapper
@XmlElement(name="channel")
public List<String> getChannels() {
return channels;
}
}
指定MOXy为JAXB Provider(jaxb.properties)
要将MOXy指定为JAXB提供程序,您需要包含一个名为的文件jaxb.properties
在与您的域模型相同的包中,带有以下条目(请参阅:):
To specify MOXy as your JAXB provider you need to include a file called jaxb.properties
in the same package as your domain model with the following entry (see: ):
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示代码
在下面的演示代码中,我们将同一个实例输出到XML和JSON。
In the demo code below we will output the same instance to both XML and JSON.
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.MarshallerProperties;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Root root = new Root();
root.getChannels().add("Test A");
root.getChannels().add("Test B");
// Output XML
marshaller.marshal(root, System.out);
// Output JSON
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
marshaller.setProperty(MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
marshaller.marshal(root, System.out);
}
}
输出
以下是运行演示代码的输出:
Below is the output from running the demo code:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<channels>
<channel>Test A</channel>
<channel>Test B</channel>
</channels>
</root>
{
"channels" : [ "Test A", "Test B" ]
}
更多信息