尝试在Jersey中使用Pojo对象处理JSON和FORM帖子

时间:2013-07-30 20:45:54

标签: java json jersey

我正在尝试使用jersey处理JSON和FORM帖子以及pojo对象上的jsr 303验证

@POST
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED})
@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_HTML})
public Response registration(@Valid User registration) {
    UserServiceWrapper.getImpl().registrateUser(registration);
    return Response.ok(registration).build();
}

目前json的所有内容都运行良好,但是表单帖子失败了;

  

HTTP / 1.1 415不支持的媒体类型

我不知道如何解决这个问题,并将POJO对象保留在界面中。有人有想法吗?

1 个答案:

答案 0 :(得分:1)

默认的jersey 2.0框架似乎不支持这个,修复此问题是创建自己的MessageBodyReader,见下文;

@Provider
public class FormDataReader implements MessageBodyReader<Object> {

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

    @Override
    public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
        String queryString = IOUtils.toString(entityStream);

        Object result = type.newInstance();
        BeanUtils.copyProperties(result, getUrlParameters(queryString));
        return result;
    }

    public static Map<String, String> getUrlParameters(String queryString)
            throws UnsupportedEncodingException {
        Map<String, String> params = new HashMap<String, String>();
        for (String param : queryString.split("&")) {
            String pair[] = param.split("=");
            String key = URLDecoder.decode(pair[0], "UTF-8");
            String value = "";
            if (pair.length > 1) {
                value = URLDecoder.decode(pair[1], "UTF-8");
            }
            params.put(new String(key), new String(value));
        }
        return params;
    }

}