以下是可以根据您运行的环境执行此操作的几种方法:
独立示例
使用标准 JAXB API 时,MOXy 将在编组为 JSON 时包含根元素。可以使用该JAXBContextProperties.JSON_INCLUDE_ROOT
属性更改此行为。false
如果在创建时已设置为,JAXBContext
您可以将其设置回true
。Marshaller
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.jaxb.MarshallerProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(2);
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
JAXBContext jc = JAXBContext.newInstance(new Class[] {Foo.class}, properties);
Foo foo = new Foo();
foo.setBar("Hello World");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
marshaller.marshal(foo, System.out);
}
}
JAX-RS 和MOXyJsonProvider
MOXy 包含一个MessageBodyReader
/的实现,MessageBodyWriter
它可以很容易地将 MOXy 配置为您的 JSON 绑定提供程序。默认情况下MOXyJsonProvider
配置为不包含根元素。Application
您可以通过在 JAX-RS类上设置配置实例来更改此设置,如下所示。
import java.util.*;
import javax.ws.rs.core.Application;
import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
public class FooApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> set = new HashSet<Class<?>>(1);
set.add(ExampleService.class);
return set;
}
@Override
public Set<Object> getSingletons() {
MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider();
moxyJsonProvider.setIncludeRoot(true);
HashSet<Object> set = new HashSet<Object>(1);
set.add(moxyJsonProvider);
return set;
}
}
了解更多信息
MOXy 作为 Jersey/GlassFish 中的默认 JSON 绑定提供程序
如果您使用 MOXy 作为 Jersey/GlassFish 的默认 JSON 绑定提供程序,您可以使用MoxyJsonConfig
该类,如下所示:
import javax.ws.rs.ext.*;
import org.glassfish.jersey.moxy.json.MoxyJsonConfig;
@Provider
public class MOXyJsonContextResolver implements ContextResolver<MoxyJsonConfig> {
private final MoxyJsonConfig config;
public MOXyJsonContextResolver() {
config = new MoxyJsonConfig()
.setIncludeRoot(true);
}
@Override
public MoxyJsonConfig getContext(Class<?> objectType) {
return config;
}
}
了解更多信息