我正在try 使用@RestController,它以@PathVariable返回JSON格式的特定对象,以及正确的状态代码.到目前为止,代码将以JSON格式返回对象,因为默认情况下,它使用的是Jackson库中内置的Spring 4.

However I do not know how to make it so it will give a message to the user saying we want an api variable, then JSON data, then Error code (Or success code depending if all went well). Example output would be:

请输入api值作为参数(注意,如果需要,也可以使用JSON)

{"id":2,"api":"3000105000"…}(注意这将是JSON响应对象)

Status Code 400 (OR proper status code)


The url with parameter look like this

http://localhost:8080/gotech/api/v1/api/3000105000

到目前为止,我掌握的代码如下:

@RestController
@RequestMapping(value = "/api/v1")
public class ClientFetchWellDataController {

    @Autowired
    private OngardWellService ongardWellService;

    @RequestMapping(value = "/wells/{apiValue}", method = RequestMethod.GET)
    @ResponseBody
    public OngardWell fetchWellData(@PathVariable String apiValue){
        try{
            OngardWell ongardWell = new OngardWell();
            ongardWell = ongardWellService.fetchOneByApi(apiValue);
    
            return ongardWell;
        }catch(Exception ex){
            String errorMessage;
            errorMessage = ex + " <== error";
            return null;
        }
    }
}

推荐答案

@RestController不适合这样做.如果需要返回不同类型的响应,请使用ResponseEntity<?>,在这里可以显式设置状态代码.

ResponseEntity中的body将以与任何@ResponseBody注释方法的返回值相同的方式处理.

@RequestMapping(value = "/wells/{apiValue}", method = RequestMethod.GET)
public ResponseEntity<?> fetchWellData(@PathVariable String apiValue){
    try{
        OngardWell ongardWell = new OngardWell();
        ongardWell = ongardWellService.fetchOneByApi(apiValue);

        return new ResponseEntity<>(ongardWell, HttpStatus.OK);
    }catch(Exception ex){
        String errorMessage;
        errorMessage = ex + " <== error";
        return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
    }
}

注意,在@RestController注释类中,@RequestMapping方法不需要@ResponseBody.

Json相关问答推荐

将json数组反序列化为选项 struct

使用PowerShell解析文件并获取特定行的值

使用快速json库编写json可以消除所有缩进

无法访问id的第三级json

使用 jq 如何更改键的值?

Jolt - 如何比较 if else 条件的两个值

如何使用jq按键 Select 并获取整个json输出来更改json中的多个值

jq - 将父键值提取为子元素旁边的逗号分隔值

如何在不使用 Newtonsoft.JSON 的情况下序列化/反序列化

从字节解码 JSON 数据,将 float 值更改为 int

Powershell 7.2:ConvertFrom-Json - 日期处理

如何在 Dart 中与多个 map (字典)相交

如何将动态复杂 json 解析为dart 对象或模型

SwiftUI:如何使用 0 索引数组键为 JSON 添加类型

如何使用 LINQ 在 C# 中重构对象?

如何从Typescript 中的json响应中获取日期对象

使用 jq,将对象数组转换为具有命名键的对象

如何使用 Newtonsoft.Json 包在 C#(4.0) 中解析我的 json 字符串?

AJAX 将 JavaScript 字符串数组发布到 JsonResult 作为 List 总是返回 Null?

JSON JQ 如果没有 else