简体   繁体   English

春季球衣POST序列化bean

[英]spring jersey POST serialized bean

Is there any way to get POST request body as serialized bean instead of raw json string ? 有什么方法可以将POST请求正文作为序列化的bean代替原始的json string吗? for example: 例如:

    @POST
    @Path(ResourceEndpoints.POST_USER_REGISTER)
    @Produces(MediaType.APPLICATION_JSON)
    public Response register(@RequestBody UserObject user) {
    ...

Then I would not have to write json serializer boiler-plate code in each request. 然后,我将不必在每个请求中编写json序列化器样板代码。

Currently I have to do like this: 目前,我必须这样做:

    @POST
    @Path(ResourceEndpoints.POST_USER_REGISTER)
    @Produces(MediaType.APPLICATION_JSON)
    public Response register(@RequestBody String userObjectJson) {
        Gson gson = new Gson();
        UserObject userObject = gson.fromJson(userObjectJson, UserObject.class);

If you must stick to Gson, you need to write a MessageBodyReader / MessageBodyWriter pair to handle deserialization/serialization. 如果必须坚持使用Gson,则需要编写MessageBodyReader / MessageBodyWriter对以处理反序列化/序列化。 This is how the request stream is converted into our domain objects and domain objects serialized to the response stream. 这就是将请求流转换为我们的域对象和序列化为响应流的域对象的方式。

You can find a good explanation about this subject here and you can find a simple implementation here at Integrating Gson into a JAX-RS based application . 您可以在这里找到关于此主题的很好的解释,并在此处将Gson集成到基于JAX-RS的应用程序中找到一个简单的实现。 I will post the implementation at the bottom (in case the side ever goes down). 我将在底部发布实现(以防万一)。

However you register all your other Jersey components, ie resource classes and providers, register this GsonMessageBodyHandler the same way. 但是,您注册所有其他Jersey组件(即资源类和提供程序)时, GsonMessageBodyHandler以相同的方式注册此GsonMessageBodyHandler If you have package scanning enabled, the class should be automatically picked up from the @Provider annotation. 如果启用了包扫描,则应从@Provider批注中自动选择@Provider In any case the @RequestBody annotation shouldn't be needed (I don't work much with Spring, but I would guess it's ignored either way). 无论如何,都不需要@RequestBody批注(我对Spring的工作不多,但是我想无论哪种方式都将其忽略)。

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Provider
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public final class GsonMessageBodyHandler implements MessageBodyWriter<Object>,
    MessageBodyReader<Object> {

  private static final String UTF_8 = "UTF-8";

  private Gson gson;

  private Gson getGson() {
    if (gson == null) {
      final GsonBuilder gsonBuilder = new GsonBuilder();
      gson = gsonBuilder.create();
    }
    return gson;
  }

  @Override
  public boolean isReadable(Class<?> type, Type genericType,
      java.lang.annotation.Annotation[] annotations, MediaType mediaType) {
    return true;
  }

  @Override
  public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws Exception, ApplicationException {
    InputStreamReader streamReader = new InputStreamReader(entityStream, UTF_8);
    try {
      Type jsonType;
      if (type.equals(genericType)) {
        jsonType = type;
      } else {
        jsonType = genericType;
      }
      return getGson().fromJson(streamReader, jsonType);
    } finally {
      streamReader.close();
    }
  }

  @Override
  public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    return true;
  }

  @Override
  public long getSize(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    return -1;
  }

  @Override
  public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8);
    try {
      Type jsonType;
      if (type.equals(genericType)) {
        jsonType = type;
      } else {
        jsonType = genericType;
      }
      getGson().toJson(object, jsonType, writer);
    } finally {
      writer.close();
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM