如何使用JAXB将属性对象转换为JSON对象 [英] How to Convert a Properties Object to JSON Object with JAXB

查看:270
本文介绍了如何使用JAXB将属性对象转换为JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想接受并响应REST应用程序中的JSON对象。我需要发送和接收的数据位于.properties文件中。我已经读过它们,现在位于属性对象(来自 java.util.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?

我正在使用Jax- rslog在Weblogic服务器中。

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,所以我不知道是什么版本的它使用的泽西(1.x或2.x),但是1.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已经将属性对象反序列化并序列化为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("\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

对于配置,您只需配置POJOMapping功能并注册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 。如果你想要pojos的编组依赖于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.

这篇关于如何使用JAXB将属性对象转换为JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆