ajax调用在SpringBoot中返回值jsonarray.fromobject(数据)时出现错误500

kgqe7b3p  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(268)

我正在尝试将一些jsonarray值添加到我的ajax响应主体中。但它总是给错误500。我可以看到调用在控制器上,并且还打印了值。但出于某种原因,它不会进入ajax响应主体。如果我返回这个类,那么我可以看到ajax调用运行良好,但是当我试图将这些值传递给jsonarray时。我用的是Spring Boot。我得到了这个类型错误。
得到http://localhost:5000/报告/id?=2500
ajax调用:

$.ajax({
           type: "GET",
           url: "/report",
           data: {
             id: id
            },
           success: function (response) {
                console.log(response)

      },
   });

控制器:

@RestController

 @Autowired
 ReportDAO reportDao;

 @GetMapping(value = "/report")
 public @ResponseBody JSONArray getReport(@RequestParam(value="id") Integer id) {
  JsonArray report = new JSONArray();
  try {
     report = JSONArray.fromObject(reportDao.getReportById(id));
 } catch(Ex e){

  }
  System.out.println(report); // this is returing the value but not in the main ajax resposne call
   return report;
}

我在控制器上得到的数据是这样的:

[{
  "dataUrl: "va",
  "id": 1,
  "status": "active",
  "dataJson": "[{
    "id": 1,
    "name": "Jon"
   }]

}]
yh2wf1be

yh2wf1be1#

因此,看起来springboot很可能试图将jsonarray中的内部工作字段序列化为json,这不是您想要的。
spring在内部使用jackson(json解析器)在json和java类之间自动转换。因此,如果您返回dao类型而不是jsonarray,spring会在幕后调用jackson,比如 new ObjectMapper().writeValueAsString(myDAOReturnType) 比如:

@GetMapping(value = "/report/{id}")
public @ResponseBody MyDAOType getReport(@PathVariable(value="id") Integer id) {
   MyDAOType report;
   try {
      report = reportDao.getReportById(id);
   } catch(Ex e){
        // handle error
   }
   return report;
}

其中mydaotype是从 reportDao.getReportById(id); 注意:在我的示例中,我还切换到使用pathvariable,因为这似乎更适合您的场景。

zmeyuzjn

zmeyuzjn2#

那是因为你做了错误的ajax调用。您的控制器设置为期望 id 作为请求参数而不是主体。这又意味着你应该点击的网址应该是: /report/{id} 而不是将其作为请求主体的一部分传递。这反过来又会导致 500 您看到的错误,因为spring排除了参数 RequestParam#required 价值是 true 默认情况下。
最后不行了,虽然你可以用 GET 对于请求机构,我建议不要这样做,因为这不是好的做法。

相关问题