为什么我无法在 Spring Rest 中将字符串列表作为 json 响应发送?

问题描述 投票:0回答:1

我构建了一个简单的弹簧休息应用程序,只有一个休息控制器。

DemoRestController.java:


import java.util.Arrays;
import java.util.List;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class DemoRestController {
    
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello";
    }
    
    @GetMapping(value="/get-fruits", consumes=MediaType.ALL_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
    public List<String> getFruits() {
        List<String> fruits = Arrays.asList("Apple", "Banana", "Pear");
        return fruits;
    }
}

运行此应用程序时,我得到:

org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver logException
WARNING: Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class java.util.Arrays$ArrayList] with preset Content-Type 'null']

我已经在

WebContent\WEB-INF\lib
中添加了所有用于json序列化和反序列化的Jackson库。我现在没有使用maven。为了学习目的,我手动添加了Spring和Jackson的依赖。

内置类型数组(例如字符串数组)或内置类型列表(字符串列表)等类型不会自动转换为 json 格式吗?

如果我们想要发送自定义类型/实体(例如学生列表)作为响应,我们是否使用

ResponseEntity<T>
?请给我一些例子。

非常感谢。

java json spring-boot microservices spring-restcontroller
1个回答
0
投票

我像这样使用 List<> 响应

  @GetMapping("/YOUR_API_URL")  
  public Response<Object> YOUR_METHOD_NAME(@RequestParam String id){
     List<RESPONSE_CLASS>response = YOUR_SERVICE.YOUR_SERVICE_METHOD(id);
     returnResponse.ok().setData(response).setMessage("YOUR_RESPONSE_MESSAGE");  
}

这是我的响应课程

@Getter
@Setter
@Accessors(chain = true)
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Response<T> {

    private Status status;
    private T data;
    private String message;
}

你的代码也适合我

    @GetMapping(value="/get-fruits",
consumes=MediaType.ALL_VALUE,
produces=MediaType.APPLICATION_JSON_VALUE)
public List<String> getFruits(){
  return Arrays.asList("Apple", "Banana", "Pear");
}

这是您的代码响应

[
  "Apple",
  "Banana",
  "Pear"
]

希望您能从中得到答案...!

© www.soinside.com 2019 - 2024. All rights reserved.