如何使用JAXB将属性对象转换为JSON对象

我想接受并响应REST应用程序中的JSON对象。 我需要发送和接收的数据位于.properties文件中。 我已经阅读过它们,现在它们属于一个Properties对象(来自java.util.Properties )。 有没有一种方法可以编组和解组Properties对象,而无需实现新类?

我在Weblogic服务器中使用Jax-rs API。

 @POST @Path("{id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public JSONObject getbyID(@PathParam("id")JSONObject inputJsonObj) { //marshalling and unmarshalling goes here } 

不太熟悉WebLogic,所以我不知道它使用的是什么版本的Jersey(1.x或2.x),但是使用1.x你可以简单地添加这个依赖

  com.sun.jersey jersey-json ${jersey-version}  

这将取决于jackson。 Jackson已经将Properties对象反序列化并序列化为JSON对象。

这是一个简单的测试

资源

 @Path("/properties") public class PropertiesResource { @GET @Produces(MediaType.APPLICATION_JSON) public Response getProperties() throws Exception { FileInputStream fis = new FileInputStream("test.properties"); Properties props = new Properties(); props.load(fis); return Response.ok(props).build(); } @POST @Consumes(MediaType.APPLICATION_JSON) public Response postProperties(Properties properties) { StringBuilder builder = new StringBuilder(); for (String key: properties.stringPropertyNames()) { builder.append(key).append("=") .append(properties.getProperty(key)).append("\n"); } return Response.created(null).entity(builder.toString()).build(); } } 

测试

 public void testMyResource() throws Exception { ClientConfig config = new DefaultClientConfig(); config.getClasses().add(JacksonJsonProvider.class); config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client c = Client.create(config); WebResource resource = c.resource(Main.BASE_URI).path("properties"); String json = resource.accept("application/json").get(String.class); System.out.println(json); FileInputStream fis = new FileInputStream("test.properties"); Properties props = new Properties(); props.load(fis); String postResponse = resource.type("application/json").post(String.class, props); System.out.println(postResponse); } 

结果:

 // from get {"prop3":"value3","prop2":"value2","prop1":"value1"} // from post prop3=value3 prop2=value2 prop1=value1 

对于配置,您只需配置POJOMappingfunction并注册Jackson提供程序

编程

 public class JerseyApplication extends ResourceConfig { public JerseyApplication() { packages(...); getProviderClasses().add(JacksonJsonProvider.class); getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); } } 

web.xml中

  com.sun.jersey.api.json.POJOMappingFeature true  

使用Jersey 2.x ,它有点简单。 我们只需要这个提供商

  com.fasterxml.jackson.jaxrs jackson-jaxrs-json-provider 2.4.0  

并注册相同的JacksonJaxbJsonProvider (虽然不同的包,类名是相同的)。 不需要Pojo映射function。


注意:在这两种情况下,都有两个Jackson提供者,一个JacksonJsonProvider和一个JacksonJaxbJsonProvider 。 如果你想要pojos的编组依赖于JAXB注释,那么你应该注册后者。