springboot中返回list会被自动转为字符串的问题

为什么springboot返回list会默认将list转成字符串返回

package com.example.springboot_structure.controller;

import com.example.springboot_structure.GetBeanUtil;
import com.example.springboot_structure.entity.Project;
import com.example.springboot_structure.entity.ProjectCreat;
import com.example.springboot_structure.pipe2.ProjectWriter;
import com.example.springboot_structure.utils.RequestWrapper;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@CrossOrigin
@RestController
public class PeojectController {
    @RequestMapping(value = "/project/inProject",method = RequestMethod.POST)
    public String inProject(HttpServletRequest request){
        ServletRequest requestWrapper = new RequestWrapper((HttpServletRequest) request);
        System.out.println(((RequestWrapper) requestWrapper).getBody());
        String []str = ((RequestWrapper) requestWrapper).getBody().split("&");
        String []data = new String[str.length];
        ProjectCreat pc = ProjectCreat.getProjectCreat();
        for (int i = 0;i < str.length;i++) {
            data[i] = str[i].substring(str[i].indexOf("=") + 1);
        }
        Project project = pc.cProject(data[0],Integer.parseInt(data[1]),data[2],data[3],data[4]);
        if(project != null){
            ProjectWriter write = GetBeanUtil.getBean(ProjectWriter.class);
            write.insertSingle(project);
            return "创建成功";
        }
        else
            return "创建失败";
    }
    @RequestMapping(value = "/project/findProject",method = RequestMethod.POST,produces = MediaType.APPLICATION_PROBLEM_JSON_VALUE)
    public List<Project> findProject(String gid, HttpServletRequest request){
        ProjectWriter writer = GetBeanUtil.getBean(ProjectWriter.class);
        List<Project> projectList = writer.findAll(Integer.parseInt(gid));
//        List<Project> projectList = writer.findAll(Integer.parseInt(temstr));
//        List<Project> projectList = writer.findAll(Integer.parseInt(gid));
        return projectList;
//        return "ceshi";
    }
}


以上是controller代码,list被转成字符串后前端根本无法解析了

采用使用官方提供的JSONArray与JSONObject解析JSON字符串.

你的类上用了RestController注解,相当于在方法上加了ResponseBody注解,所以就会将返回的对象自动用默认的序列化返回给前端。
如果你没有单独指定序列化的话,那就是转成json字符串返回前端了。

回答部分参考、引用ChatGpt以便为您提供更准确的答案:

Spring Boot默认将List转换为字符串返回的原因是,当控制器方法的返回类型为String时,Spring Boot会将返回值作为响应的正文内容进行处理。由于List是一个集合类型,它在转换为字符串时会使用默认的toString()方法,将List中的元素连接成一个字符串,然后将这个字符串作为响应返回给客户端。

如果您希望以JSON格式返回List,可以使用Spring Boot提供的ResponseEntity类或@ResponseBody注解来指定返回值的数据格式。例如,您可以将方法返回类型更改为ResponseEntity<List>,然后使用ResponseEntity.ok(projectList)来构建响应。

另外,您的控制器代码中,findProject方法的参数中包含了一个String gid,但是在请求中并没有传递这个参数,可能会导致方法无法正常执行。您可以通过修改请求的方式,将gid作为请求参数传递给findProject方法。

以下是修改后的示例代码:

@RequestMapping(value = "/project/findProject", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Project>> findProject(@RequestParam("gid") String gid, HttpServletRequest request) {
    ProjectWriter writer = GetBeanUtil.getBean(ProjectWriter.class);
    List<Project> projectList = writer.findAll(Integer.parseInt(gid));
    return ResponseEntity.ok(projectList);
}

请注意,这只是一个示例,您可能需要根据您的实际需求进行适当的调整。

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这篇文章:Spring Boot在Controller传入List集合解决办法 也许能够解决你的问题,你可以看下
  • 除此之外, 这篇博客: springboot接口参数为List中的 代码实现请求 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:
    public void queryLiveCourseInfoTest(){
       JSONArray jsonArray = new JSONArray();
       JSONObject json1 = new JSONObject();
       json1.put("dn","123");
       json1.put("bossCode","34455");
       jsonArray.add(json1);
       JSONObject json2 = new JSONObject();
       json2.put("dn","234");
       json2.put("bossCode","66666");
       jsonArray.add(json2);
    
       String arr = jsonArray.toJSONString();
       System.out.println("请求参数:"+arr);
    
       String url = nativUrl+"";
       try {
          HttpHeaders headers = new HttpHeaders();
          MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
          headers.setContentType(type);
          HttpEntity<ElecMeterDataApi> entity = new HttpEntity<ElecMeterDataApi>(arr,headers);
          String res = restTemplate.postForObject(url, entity, String.class);
          log.info("结果:"+res);
       } catch (RestClientException e) {
          log.error("请求异常" + e.getMessage());
       }
    }
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^