一、需求
实际项目中,经常存在不同行,数据结构不一样的情况,但是又不能统一返回字符串格式,需要处理这种问题。
例如:
序号 | 名称 | 面积/金额/占比 | 分数/目标/是否合格 | 联系方式 |
---|---|---|---|---|
1 | 面积 | 89.87 | 65.5 | – |
2 | 销售达成率 | 67% | 不合格 | – |
3 | 占比 | 90% | 10 | 13908768723 |
二、创建父类
import lombok.Data;
@Data
public class ParentData {
private String id;
private String name;
}
三、创建子类
有几行创建几个,如果有相同的行的数据结构,不需要重复创建
1、第一行
import lombok.Data;
import java.math.BigDecimal;
@Data
public class ChildOneData extends ParentData {
private BigDecimal amt;
private BigDecimal score;
}
2、第二行
import lombok.Data;
import java.math.BigDecimal;
@Data
public class ChildTwoData extends ParentData {
private String amt;
private String score;
}
3、第三行
import lombok.Data;
import java.math.BigDecimal;
@Data
public class ChildThreeData extends ParentData {
private String amt;
private BigDecimal score;
private BigDecimal phone;
}
四、编写测试类
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* @Author:
* @Description
* @Date: 下午4:16 2024/3/29
*/
@RestController
@RequestMapping("/parent")
public class TestParentChildController {
@GetMapping("/test")
public List<ParentData> list() {
List<ParentData> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
switch (i) {
case 1: //表格第一行
ChildOneData childOneData = new ChildOneData();
childOneData.setAmt(new BigDecimal("89.87"));
childOneData.setScore(new BigDecimal("65.5"));
childOneData.setId(i+"");
childOneData.setName("面积");
list.add(childOneData);
break;
case 2://表格第二行
ChildTwoData childTwoData = new ChildTwoData();
childTwoData.setAmt("67%");
childTwoData.setScore("不合格");
childTwoData.setId(i+"");
childTwoData.setName("销售达成率");
list.add(childTwoData);
break;
case 3://表格第三行
ChildThreeData childFourData = new ChildThreeData();
childFourData.setAmt("90%");
childFourData.setScore(new BigDecimal("10"));
childFourData.setPhone(new BigDecimal("13908768723"));
childFourData.setId(i+"");
childFourData.setName("同比");
list.add(childFourData);
break;
}
}
return list;
}
}
五、测试结果
启动项目,浏览器访问 http://localhost:8888/parent/test
[
{
"amt": 89.87,
"id": "1",
"name": "面积",
"score": 65.5
},
{
"amt": "67%",
"id": "2",
"name": "销售达成率",
"score": "不合格"
},
{
"amt": "90%",
"id": "3",
"name": "同比",
"phone": 13908768723,
"score": 10
}
]