如何访问Spring休息控制器中的普通json主体?

时间:2013-07-25 19:24:13

标签: spring rest spring-mvc controller

拥有以下代码:

@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String greetingJson(@RequestBody String json) {
    System.out.println("json = " + json); // TODO json is null... how to retrieve plain json body?
    return "Hello World!";
}

尽管在正文中发送了json,但String json参数始终为null。

注意我不想要自动类型转换,我只想要普通的json结果。

这例如有效:

@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String greetingJson(@RequestBody User user) {
    return String.format("Hello %s!", user);
}

可能我可以使用ServletRequest或InputStream作为参数来检索实际的身体,但我想知道是否有更简单的方法?

5 个答案:

答案 0 :(得分:56)

我发现的最佳方法是:

@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String greetingJson(HttpEntity<String> httpEntity) {
    String json = httpEntity.getBody();
    // json contains the plain json string

如果还有其他选择,请告诉我。

答案 1 :(得分:12)

你可以使用

@RequestBody String pBody

答案 2 :(得分:7)

只有HttpServletRequest为我工作。 HttpEntity给出了空字符串。

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;

@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String greetingJson(HttpServletRequest request) throws IOException {
    final String json = IOUtils.toString(request.getInputStream());
    System.out.println("json = " + json);
    return "Hello World!";
}

答案 3 :(得分:3)

最适合我的方式是

@RequestMapping(value = "/greeting", method = POST, consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String greetingJson(String raw) {
    System.out.println("json = " + raw);
    return "OK";
}

答案 4 :(得分:1)

如果您有数十种方法需要将HTTP正文作为JSON并将其转换为自定义数据类型,那么这是在框架上实现支持的更好方法

public static class Data {
    private String foo;
    private String bar;
}

//convert http body to Data object.
//you can also use String parameter type to get the raw json text.
@RequestMapping(value = "/greeting")
@ResponseBody
public String greetingJson(@JsonBody Data data) {
    System.out.println(data);
    return "OK";
}

请注意,我们使用的是用户定义的注释@JsonBody

// define custom annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface JsonBody {
    String encoding() default "utf-8";
}

//annotation processor for JsonBody 
@Slf4j
public class JsonBodyArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(JsonBody.class) != null;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
                              WebDataBinderFactory binderFactory) throws Exception {
        JsonBody annotation = parameter.getParameterAnnotation(JsonBody.class);
        assert annotation != null;
        ServletRequest servletRequest = webRequest.getNativeRequest(ServletRequest.class);
        if (servletRequest == null) {
            throw new Exception("can not get ServletRequest from NativeWebRequest");
        }
        String copy = StreamUtils.copyToString(servletRequest.getInputStream(), Charset.forName(annotation.encoding()));
        return new Gson().fromJson(copy, parameter.getGenericParameterType());
    }
}

// register the annotation processor
@Component
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new JsonBodyArgumentResolver());
    }
}