java - Spring Jersey POST 序列化 bean

标签 java spring jersey

有什么方法可以将 POST 请求正文作为序列化 bean 而不是原始 json string 获取? 例如:

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

然后我就不必在每个请求中编写 json 序列化器样板代码。

目前我必须这样做:

    @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);

最佳答案

如果您必须坚持使用Gson,则需要编写MessageBodyReader/MessageBodyWriter对来处理反序列化/序列化。这就是请求流转换为域对象并将域对象序列化为响应流的方式。

您可以找到有关此主题的很好的解释 here你可以找到一个简单的实现 here at Integrating Gson into a JAX-RS based application 。我将在底部发布实现(以防侧面下降)。

无论您如何注册所有其他 Jersey 组件,即资源类和提供程序,请以相同的方式注册此 GsonMessageBodyHandler。如果您启用了包扫描,则应该自动从 @Provider 注释中获取该类。在任何情况下,都不需要 @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();
    }
  }
}

关于java - Spring Jersey POST 序列化 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30456497/

相关文章:

java - 使用 jersey 的 JAXB 解码失败

java - 如何以编程方式设置注释属性/属性?

java - Controller 级别的两个 try catch block

java - 简单的; Java 中不能在方法本身之前调用方法吗?

java - HTTP 状态 400 - 客户端发送的请求在语法上不正确

spring - Spring Data REST 中带有验证错误的空消息

java - 如何使用 Spring 将 null 作为方法参数连接?

java - 无法让 Jersey 映射工作

java - 加载具有父子关系的类时出现 LinkageError

java - 无法实例化类 : com. sun.enterprise.naming.SerialInitContextFactory