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

2022-01-21 00:00:00 json java jax-rs jersey jersey-2.0

我想在 REST 应用程序中接受和响应 JSON 对象.我需要发送和接收的数据位于 .properties 文件中.我已经阅读了它们,现在位于 Properties 对象中(来自 java.util.Properties).有没有办法在不实现新类的情况下编组和解组 Properties 对象?

I want to accept and respond JSON objects in a REST Application. The data I need to send and receive are in a .properties file. I have already read them and are now in a Properties Object(From java.util.Properties). Is there a way to marshal and unmarshal Properties Objects, without implementing a new class?

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

I am using Jax-rs API in a Weblogic server.

@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.x 你可以简单地添加这个依赖项

Not too familiar with WebLogic, so I don't know what version of Jersey it used (1.x or 2.x), but with the 1.x you can simply add this dependency

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>${jersey-version}</version>
</dependency>

这将取决于杰克逊.Jackson 已经将 Properties 对象反序列化并序列化为 JSON 对象.

which will depend on Jackson. Jackson already deserializes and serializes the Properties object to a JSON object.

这是一个简单的测试

资源

@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("
");
        }
        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

配置方面,只需要配置POJOMapping Feature并注册Jackson提供者

For the configuration, you just need to configure the POJOMapping Feature and register the Jackson provider

程序化

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

web.xml

<init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>true</param-value>
</init-param>

<小时>

使用 Jersey 2.x,它稍微简单一些.我们只需要这个提供者


With Jersey 2.x, it's a little bit simpler. We just need this provider

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.4.0</version>
</dependency>

并注册相同的JacksonJaxbJsonProvider(虽然包不同,但类名相同).无需 Pojo 映射功能.

And register the same JacksonJaxbJsonProvider (though different package, the class name is the same). No Pojo Mapping Feature needed.

注意:在这两种情况下,都有两个 Jackson 提供程序,一个 JacksonJsonProvider 和一个 JacksonJaxbJsonProvider.如果您希望 pojo 的编组依赖于 JAXB 注释,那么您应该注册后者.

Note: In both cases, there are two Jackson providers, a JacksonJsonProvider and a JacksonJaxbJsonProvider. If you want the marshalling of pojos to depend on JAXB annotations, then you should register the latter.

相关文章