【发布时间】:2016-03-30 10:36:18
【问题描述】:
在我问我的问题之前,我必须说我已经阅读了 20 多个关于这个问题的问题和文章,但没有一个可以解决它。
我的问题是我在 java 中有一个这样的宁静服务器:
@RequestMapping (value = "/downloadByCode", method = RequestMethod.POST)
@ResponseBody
public void downloadByCode(@RequestBody final String stringRequest, final HttpServletResponse response)
{
try
{
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode jsonRequest = objectMapper.readValue(stringRequest, JsonNode.class);
// ...
// some processings here to create the result
// ....
final ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(result);
// Flush the result
outputStream.flush();
}
catch (final Exception exception)
{
LOG.debug("Exception Thrown [downloadByCode]", exception);
}
}
我已经尝试了不同的方法来使用 jquery 将 json 发送到这个服务器(但它们都会产生错误):
$.ajax({
url:"/downloadByCode",
type:"POST",
data: JSON.stringify({"name":"value"}) });
415 "错误信息" : "内容类型 'application/x-www-form urlencoded;charset=UTF-8' not supported", "type" : "HttpMediaTypeNotSupportedError"
所以我尝试通过添加 contentType 来修复它:
$.ajax({
url:"/downloadByCode",
contentType:"application/json",
type:"POST",
data: JSON.stringify({"name":"value"}) });
400“错误消息”:“无法为类实例化 JAXBContext [类java.lang.String]:空;嵌套异常是 javax.xml.bind.JAXBException\n - 带有链接 异常:\n[java.lang.NullPointerException", "type" :"HttpMessageConversionError"
我尝试直接发送 json 对象而不是 JSON.stringify,它给出了相同的 400 错误。
我尝试向@requestMapping 添加不同的消费,但仍然没有成功。
我尝试定义自己的类而不是 JsonNode,但它并没有改变任何东西。
有什么想法吗?
【问题讨论】:
-
您是否尝试过将 @RequestBody 参数类型更改为 Map
或创建具有单个“名称”属性的类并将其用作类型(如 Vinh Vo 所建议的那样)? -
@NTyler,我从未尝试过 Map
,我现在要尝试。谢谢你的建议 -
Vinh Vo 方法会产生以下错误:
Could not instantiate JAXBContext for class [$InputData]: \r\n Exception Description: $InputData requires a zero argument constructor or a specified factory method. Note that non-static inner classes do not have zero argument constructors and are not supported. -
您可能需要按照 Vinh Vo 的建议使用 POJO 类。将类声明为静态或将其放在单独的文件中,您应该已准备就绪。
-
赏金应该去Vinh Vo,他的回答是正确的,而且是第一位的。该类只需要是静态的,因为您将其设置为内部类,如果您在自己的文件中创建该类,则不需要静态修饰符。
标签: java jquery json ajax restful-architecture