【问题标题】:RestAPI Creating Nested JsonRest API 创建嵌套 Json
【发布时间】: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 请求及其 @PostMapping Spring 注释。
  • 你能举例说明如何使用@PostMapping 来处理嵌套的json吗?
  • 嵌套 JSON 作为请求正文还是嵌套 JSON 作为响应正文?

标签: java spring rest


【解决方案1】:

您需要一个根据要发送到 REST API 的信息对用例进行建模的类。大致如下:

public class YourNestedClass {
    private RestAPIState player1;
    private RestAPIState player2;
    // ...
}

然后你需要在你的Controller中使用这个类作为POST端点的参数:

@RestController
public class RestAPIController {

    @PostMapping("/whatever-path")
    public YourResponseClass whatever(@RequestBody YourNestedClass yourNestedClass) {
        (...)
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    相关资源
    最近更新 更多