【发布时间】:2022-01-23 03:02:45
【问题描述】:
我点击此链接:https://spring.io/guides/gs/rest-service/ 为我的游戏开发 REST API。基于此,我为我的游戏制作了一个“模板”REST API。这是我写的代码:
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:
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:
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);
}
}
当我转到http://localhost:8080/game 时,我得到了输出 "{"id":"123","location":[1,2],"points":5}",如预期的那样。但是,对于我的游戏,我需要知道如何编写一个函数,该函数接受输入并输出嵌套的 JSON(与上面不同),例如 "{"player1": {"id": (input), "location": (输入),“点”:(输入)},“player2”:...}”。有人可以向我解释如何做到这一点吗?非常感谢。
【问题讨论】:
-
您对
a function which takes input and outputs nested JSON的意图是什么?您想解决哪个用例? -
我正在创建一个游戏。每个玩家都有关于他们的某些信息。我希望有这样的功能,例如,当一个正方形被点击时,信息被发送到restAPI,然后其他玩家可以查询restAPI来获取这个信息。
-
那么您需要将该信息存储在某处。为了向 REST API 发送一些信息,您应该使用
POST请求及其@PostMappingSpring 注释。 -
你能举例说明如何使用@PostMapping 来处理嵌套的json吗?
-
嵌套 JSON 作为请求正文还是嵌套 JSON 作为响应正文?