在JAX-RS中将JSON解组为Java POJO [英] Unmarshal JSON to Java POJO in JAX-RS

查看:72
本文介绍了在JAX-RS中将JSON解组为Java POJO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望获得每个Json格式化调用的键和值,并将它们用作Java对象,如String或Integer,在其他客户端中我将输入
{
Name: HelloWorld
}



我会回到映射到它的Key的HelloWorld到目前为止我见过的例子但是我很难找到每个标签的作用和如何解析正文以给出上述结果

  @POST 
@Path(/ SetFeeds)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@JsonCreator

public String setFeed(String jsonBody,@ Context UriInfo uriInfo){
...代码操纵请求的主体
返回响应;

}


解决方案

第一件事你需要了解请求体解析是如何完成的。在JAX-RS中,使用。只需单独搜索它们。



然后你需要注册提供者。同样,它取决于您的JAX-RS实现以及如何处理资源类的配置。我需要查看您的应用程序配置(web.xml或Java代码)以及您正在使用的服务器来帮助解决这个问题。在大多数情况下, JacksonJsonProvider (这是读者和作者)需要注册。



一旦你有了它注册后你需要了解杰克逊如何处理序列化的基础知识。最多 basic 级别,Jackson会查找 JavaBean属性(基本的getter / setter)以匹配JSON属性。例如,如果你有这个bean属性

  public class HelloWorld {
private String name;

public String getName(){
return name;
}

public void setName(String name){
this.name = name;
}
}

JSON应该看起来像 {name:whatever} name键与bean属性相同。在Bean属性术语中,属性的名称是 get / set 之后的所有字母,第一个字母是小写的。



这几乎就是它的全部内容。现在你可以做到

  @Consumes(application / json)
public Response post(HelloWorld helloWorld){
String name = helloWorld.getName(); //应该==无论什么

返回Response.ok(helloWorld).build(); //我们也可以返回对象
}

对于更复杂的JSON格式,你应该参考到杰​​克逊的文件或在这里问一个问题。



至于注册 JacksonJsonProvider ,如果如果您遇到问题,请提供我要求的信息,即应用程序配置(web.xml或Java配置)以及您正在使用的服务器。



参见:




I am looking to get the key and value to each Json formatted call and use them as java objects such as String or Integer ,in a rest client i would enter { "Name":"HelloWorld" }

And i would get back the HelloWorld mapped to its Key so far ive seen examples but im just having trouble finding out what each tag does and how to parse the body to give the above results

@POST
    @Path("/SetFeeds")
    @Consumes(MediaType.APPLICATION_JSON)   
    @Produces(MediaType.APPLICATION_JSON) 
    @JsonCreator

        public String setFeed(String jsonBody,@Context UriInfo uriInfo){        
...Code to manipulate the body of the request 
            return response;

    } 

解决方案

First thing you need to understand is how request body parsing is done. In JAX-RS parsing (or unmarshalling/deserializing/whatever) is done with MessageBodyReaders. There are different readers that can handle different Content-Type. For instance if you have Content-Type application/octet-stream, there is a reader that will unmarshal to byte[] or File or InputStream. So the following would work out the box

@Consumes("application/octet-stream")
public Response post(File file) {}  // or `byte[]` or `InputStream`

That being said, JAX-RS implementations come with very basic readers for "easily convertible" format. For example, most requests can be converted to String, so you get that free for most Content-Types, as you are with your current code.

If we want some more complex data types, like your HelloWorld for Content-Type application/json, there is no standard reader for this. For this to work, we either need to create our own reader, or use a library that comes with a reader. Luckily, the most popular JSON framework in Java, Jackson, has implemented a JAX-RS provider that has a reader and a writer (for serialization).

Now depending on what server/JAX-RS implementation you are using, different implementations create light wrappers around the core Jackson JAX-RS module. If I knew the JAX-RS implementation you were using, I could recommend which wrapper to use, or you can forget the wrapper and just go with the basic Jackson module, which is

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

The above is a Maven dependency. If you are not using Maven, then basically you need to download all these jars.

You can find all of them here. Just search for them individually.

Then you need to register the provider. Again it depends on your JAX-RS implementation and how you are handling the configuration of your resource classes. I would need to see your application configuration (either web.xml or Java code) and maybe the server you are using to help with that. For the most part the JacksonJsonProvider (which is the reader and writer) needs to be registered.

Once you have it registered then you need to understand the basics of how Jackson handle the serializaion. At most basic level, Jackson looks for JavaBean properties (basic getter/setter) to match with JSON properties. For instance if you have this bean property

public class HelloWorld {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
} 

The JSON should look like {"name": "whatever"}. The "name" key is the same as the bean property. In Bean property terms, the name of the property is all letters after the get/set with the first letter lowercased.

That's pretty much all there is to it. Now you can do

@Consumes("application/json")
public Response post(HelloWorld helloWorld) {
    String name = helloWorld.getName();     // should == "whatever"

    return Response.ok(helloWorld).build(); // we can also return objects
} 

For more complex JSON formats, you should refer to the Jackson documentation or ask a question here on SO.

As far as the registering of the JacksonJsonProvider, if you are having trouble, please provide the information I requested, i.e. application configuration (web.xml or Java config) and the server you are using.

See Also:

这篇关于在JAX-RS中将JSON解组为Java POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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