Application :
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
json数据bean:
package com.example.demo;
public class JsonData {
public long id;
public String data = "";
public JsonData(long id, String data) {
this.id = id;
this.data = data;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setData(String data) {
this.data = data;
}
public String getData() {
return data;
}
}
控制器controller:
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class JsonTestController {
@GetMapping("/jsontest")
public JsonData myjsontest(@RequestParam(value = "name", defaultValue = "null") String name) {
return new JsonData(2021, "zhangphil");
}
}
注意,路由和函数名一一对应。
页面返回内容:
{"id":2021,"data":"zhangphil"}