[英]RestAPI Creating Nested Json
I followed this link: https://spring.io/guides/gs/rest-service/ to develop a REST API for my game.我点击此链接: https://spring.io/guides/gs/rest-service/为我的游戏开发 REST API。 Based on this, I made a "template" REST API for my game.基于此,我为我的游戏制作了一个“模板”REST API。 This is the code I wrote:这是我写的代码:
RestServiceApplication.java: RestServiceApplication.java:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestServiceApplication {
public static void main(String[] args) {
SpringApplication.run(RestServiceApplication.class, args);
}
}
RESTAPIState.java: RESTAPIState.java:
public class RestAPIState {
private String id;
private int[] location = new int[2];
private int points;
public RestAPIState (String id, int[] location, int points) {
this.id = id;
this.location = location;
this.points = points;
}
public String getId() {
return id;
}
public int[] getLocation() {
return location;
}
public int getPoints() {
return points;
}
}
RestAPIController.java: RestAPIController.java:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RestAPIController {
@GetMapping("/game")
public RestAPIState greeting() {
int[] sample = new int[2];
sample[0] = 1;
sample[1] = 2;
return new RestAPIState("123", sample, 5);
}
}
When I go to http://localhost:8080/game , I get the output "{"id":"123","location":[1,2],"points":5}", as expected.当我从 go 到http://localhost:8080/game时,我得到 output "{"id, as expected.","5}:" However, for my game I need to know how to know how to write a function which takes input and outputs nested JSON (unlike above) such as "{"player1": {"id": (input), "location": (input), "points": (input)}, "player2": ...}".但是,对于我的游戏,我需要知道如何编写一个 function ,它接受输入和输出嵌套 JSON (与上面不同),例如“{“player1”:{“id”:(输入),“位置”:(输入),“点”:(输入)},“player2”:...}”。 Could someone please explain to me how to do this?有人可以向我解释如何做到这一点吗? Thank you so much.太感谢了。
You would need a class that models your use case in terms of information to be sent to the REST API.您将需要一个 class,根据要发送到 REST API 的信息来模拟您的用例。 Something along the following lines:大致如下:
public class YourNestedClass {
private RestAPIState player1;
private RestAPIState player2;
// ...
}
And then you need to use this class as the parameter of the POST endpoint in your Controller:然后你需要使用这个 class 作为 Controller 中 POST 端点的参数:
@RestController
public class RestAPIController {
@PostMapping("/whatever-path")
public YourResponseClass whatever(@RequestBody YourNestedClass yourNestedClass) {
(...)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.