以下是一个使用Java和Spring Boot框架实现的示例代码:
首先,定义一个父对象Parent和一个子对象Child:
public class Parent {
private int id;
private String name;
private List children;
// 省略构造函数和getter/setter方法
}
public class Child {
private int id;
private String name;
// 省略构造函数和getter/setter方法
}
然后,在Spring Boot应用程序中创建一个REST控制器,包含一个GET端点,该端点返回一个父对象及其关联的所有子对象:
@RestController
public class ParentController {
@GetMapping("/parent")
public Parent getParentWithChildren() {
Parent parent = new Parent();
parent.setId(1);
parent.setName("Parent");
List children = new ArrayList<>();
Child child1 = new Child();
child1.setId(1);
child1.setName("Child 1");
children.add(child1);
Child child2 = new Child();
child2.setId(2);
child2.setName("Child 2");
children.add(child2);
parent.setChildren(children);
return parent;
}
}
在这个例子中,GET请求/parent
将返回一个父对象Parent,包括id、name和一个包含两个子对象的children列表。
你可以使用任何HTTP客户端(如浏览器或Postman)来发送GET请求到http://localhost:8080/parent
,并查看返回的JSON响应。
上一篇:暴露串行USB设备给容器