Java 使用 Spring MVC 在 REST HTTP GET 请求中传递 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24551412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing JSON objects in a REST HTTP GET request using Spring MVC
提问by TPPZ
According to this REST modeland to what I think is a consensus on REST: every REST retrievalshould be performed as a HTTP GET request. The problem now is how to treat complex JSON objects as parameters in GET requests with Spring MVC.There is also another consensus I found saying "use POST for retrievals!" just because "the big companies do this!", but I have been asked to try to stick to the "REST level 2 rules".
根据这个REST 模型以及我认为关于 REST 的共识:每个 REST检索都应该作为 HTTP GET 请求执行。 现在的问题是如何在 Spring MVC 的 GET 请求中将复杂的 JSON 对象视为参数。我发现还有另一个共识是“使用 POST 进行检索!” 只是因为“大公司这样做!”,但我被要求尝试遵守“REST 2 级规则”。
First question: am I trying to do something that make sense?
第一个问题:我是否正在尝试做一些有意义的事情?
I want to send via GET requests arrays / lists / sets of JSON objects, in Java with Spring MVC.I can not figure out what's wrong with my attempts, I have tried to add/remove double quotes, played around with the URL parameters, but I can not achieve this goal.
我想通过 GET 请求使用 Spring MVC 在 Java 中发送数组/列表/JSON 对象集。我不知道我的尝试有什么问题,我尝试添加/删除双引号,使用 URL 参数,但我无法实现这个目标。
What's wrong with the following code? The code snippet is coming from a MVC controller.
以下代码有什么问题?代码片段来自 MVC 控制器。
@RequestMapping(
value = "/parseJsonDataStructures",
params = {
"language",
"jsonBeanObject"
}, method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public HttpEntity<ParsedRequestOutputObject> parseJsonDataStructures(
@RequestParam String language,
@RequestParam CustomJsonBeanObject[] customJsonBeanObjects){
try {
ParsedRequestOutputObject responseFullData = customJsonBeanObjectService.parseJsonDataStructures(customJsonBeanObjects, language);
return new ResponseEntity<>(responseFullData, HttpStatus.OK);
} catch (Exception e) {
// TODO
}
}
I've tried multiple ways to build the URL request (always getting HTTP code 400 Bad Request), this is an example:
我尝试了多种方法来构建 URL 请求(总是得到 HTTP 代码 400 Bad Request),这是一个例子:
http://[...]/parseJsonDataStructures?language=en&jsonBeanObject={"doubleObject":10, "enumObject":"enumContent", "stringObject":"stringContent"}
The JSON object variables ar of type:
JSON 对象变量 ar 类型:
- Double (not the primitive)
- enum
- String
- 双倍(不是原始的)
- 枚举
- 细绳
I am assuming I can pass multiple jsonBeanObject
parameters one after the other.
我假设我可以jsonBeanObject
一个接一个地传递多个参数。
The jsonBeanObject
Java bean is:
在jsonBeanObject
的Java bean是:
public class CustomJsonBeanObject {
private Double doubleObject;
private CustomEnum enumObject;
private String stringObject;
/**
* Factory method with validated input.
*
* @param doubleObject
* @param enumObject
* @param stringObject
* @return
*/
public static CustomJsonBeanObject getNewValidatedInstance(Double doubleObject, CustomEnum enumObject, String stringObject) {
return new CustomJsonBeanObject
(
doubleObject ,
enumObject ,
stringObject
);
}
private CustomJsonBeanObject(Double doubleObject, CustomEnum enumObject, String stringObject) {
this.doubleObject = doubleObject;
this.enumObject = enumObject;
this.stringObject = stringObject;
}
public CustomJsonBeanObject() {}
// getter setter stuff
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
回答by Bond - Java Bond
First create a request bean which should encapsulate the parameters you expect as part of request. Will call it as SomeRequest
首先创建一个请求 bean,它应该封装您期望作为请求的一部分的参数。将其称为SomeRequest
Second in the controller use @RequestBody
instead of @RequestParam
第二个在控制器中使用@RequestBody
而不是@RequestParam
@ResponseBody public HttpEntity<ParsedRequestOutputObject> parseJsonDataStructures(@RequestBody SomeRequest someRequest) { ... }
Third use RestTemplate
as client to invoke your REST services. Sample code below -
第三次RestTemplate
用作客户端来调用您的 REST 服务。下面的示例代码 -
SomeRequest someRequest = new SomeRequest();
// set the properties on someRequest
Map<String, String> userService = new HashMap<String, String>();
RestTemplate rest = new RestTemplate();
String url = endPoint + "/parseJsonDataStructures";
ResponseEntity<SomeResponse> response = rest.getForEntity(url, someRequest,
SomeResponse.class, userService);
SomeResponse resp = response.getBody();
回答by CodeChimp
Your statement about only using GET or POST is for RESTcompletely incorrect. The HTTP method used depends on the action you are performing. For retrieval, you are supposed to use a GET, for add/create a POST, for remove/delete a DELETE, and for replace a PUT. Also, to be "true" REST you should only change state through self-documented actions provided by the server response (read up on HATEOAS). Most people don't do the latter.
您关于仅使用 GET 或 POST 的声明对于REST完全不正确。使用的 HTTP 方法取决于您正在执行的操作。对于检索,您应该使用 GET,添加/创建 POST,删除/删除 DELETE,以及替换 PUT。此外,要成为“真正的”REST,您应该只通过服务器响应提供的自记录操作来更改状态(在HATEOAS上阅读)。大多数人不会做后者。
As an aside, I tried searching for "REST level 2" and also got nothing by sites about beds and Dungeons'and'Dragons. I have personally never heard of it, so it is apparently so new that there are not a lot of sites talking about it or it may be called something else.
顺便说一句,我尝试搜索“REST level 2”,但在有关床和龙与地下城的网站上也一无所获。我个人从未听说过它,所以它显然很新,以至于没有很多网站在谈论它,或者它可能被称为其他东西。
To your point about how to send a JSON object, Spring MVC can handle that out-of-the-box. You can read up on it here, which uses the @RequestBody
to pull in the entire HTTP request body then parses it using your JSON processor of choice. There are plenty of code samples there describing how to handle lists and such.
关于如何发送 JSON 对象,Spring MVC 可以处理开箱即用的问题。您可以在此处阅读它,它使用@RequestBody
来拉入整个 HTTP 请求正文,然后使用您选择的 JSON 处理器对其进行解析。那里有很多代码示例描述了如何处理列表等。
回答by Golokesh Patra
package com.lightaria.json;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.Hymanson.databind.ObjectMapper;
@RestController
public class StatusController {
@RequestMapping("/lkg.latest")
public MainStatus stat() throws IOException{
byte[] jsonData = Files.readAllBytes(Paths.get("/home/admin/StatusPage/Downloads/JSON/lkg-latest.json"));
ObjectMapper objectMapper =new ObjectMapper();
MainStatus stat1 = objectMapper.readValue(jsonData, MainStatus.class);
System.out.println("Status\n"+stat1);
return stat1;
}
}
I have used the above method to parse a JSON file and store it as JSON object. One can easily replace the path by a URL. Hope it helps.
我已经使用上述方法解析了一个 JSON 文件并将其存储为 JSON 对象。可以很容易地用 URL 替换路径。希望能帮助到你。
Don't forget to make a application.properties file consisting port and various other configs. for ex - (to run the RESTful application on port 8090, the application.properties file should have server.port=8090.
不要忘记制作一个包含端口和其他各种配置的 application.properties 文件。例如 - (要在端口 8090 上运行 RESTful 应用程序,application.properties 文件应具有server.port=8090。