Spring Boot中EC2实例查询接口如何返回规范JSON响应
如何调整EC2实例查询接口返回规范JSON响应
你当前使用嵌套ArrayList返回数据,只会得到无字段含义的嵌套数组,调用方无法直接识别每个字段的意义,需要调整为结构化对象返回,序列化后就是带键名的规范JSON,具体调整步骤如下:
1. 定义EC2实例信息的结构化实体类
首先创建一个实体类存储EC2实例的对应属性,按需添加需要返回的字段即可:
// 可使用Lombok的@Data注解省略手动写构造、getter、setter的代码 public class Ec2InstanceInfo { private String instanceId; private String instanceType; private String state; // 还可以继续补充amiId、monitoringState等你日志中打印的字段 public Ec2InstanceInfo() {} public Ec2InstanceInfo(String instanceId, String instanceType, String state) { this.instanceId = instanceId; this.instanceType = instanceType; this.state = state; } // 以下为Getter、Setter方法 public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getInstanceType() { return instanceType; } public void setInstanceType(String instanceType) { this.instanceType = instanceType; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
2. 修改原接口的返回类型和逻辑
把原方法的嵌套ArrayList返回类型,改为存放实体类的List:
public List<Ec2InstanceInfo> getAllInstances() { boolean done = false; List<Ec2InstanceInfo> instances = new ArrayList<>(); DescribeInstancesRequest request = new DescribeInstancesRequest(); while (!done) { DescribeInstancesResult response = ec2Client.describeInstances(request); for (Reservation reservation : response.getReservations()) { for (Instance instance : reservation.getInstances()) { // 构造实体对象而非字符串列表 Ec2InstanceInfo info = new Ec2InstanceInfo(); info.setInstanceId(instance.getInstanceId()); info.setInstanceType(instance.getInstanceType()); info.setState(instance.getState().getName()); instances.add(info); // 原有日志逻辑保留即可 System.out.printf( "Found instance with id %s, " + "AMI %s, " + "type %s, " + "state %s " + "and monitoring state %s", instance.getInstanceId(), instance.getImageId(), instance.getInstanceType(), instance.getState().getName(), instance.getMonitoring().getState()); } } request.setNextToken(response.getNextToken()); if (response.getNextToken() == null) { done = true; } System.out.println("flag stats = "+done); } return instances; }
3. 序列化得到规范JSON
如果你用的是SpringBoot等自带JSON序列化的Web框架,接口直接返回上述List<Ec2InstanceInfo>,就会自动序列化为如下格式的响应:
[ { "instanceId": "i-09xxxxxxf5b82", "instanceType": "t2.nano", "state": "running" }, { "instanceId": "i-03ddxxxxx956d099", "instanceType": "t2.micro", "state": "running" } ]
如果没有使用自动序列化的框架,手动用Jackson、Gson等JSON工具序列化返回的List即可,以Jackson为例:
ObjectMapper objectMapper = new ObjectMapper(); String jsonResult = objectMapper.writeValueAsString(getAllInstances());
内容的提问来源于stack exchange,提问作者Amara
相关产品推荐
相关产品推荐

