【发布时间】:2021-09-06 13:05:06
【问题描述】:
我有一张表,其中包含省、地区和地区内的价值
数据
+------+--------+---------------------+------------+
| ID |Province| District | Codes |
+------+--------+---------------------+------------+
| 1001 | Texas | 1st | 1054 |
| 1002 | Texas | 2nd | 1055 |
| 1003 | Ohio | 1st | 3045 |
| 1004 | Ohio | 2nd | 3046 |
| 1005 | Utah | 1st | 1023 |
| 1006 | Utah | 2nd | 1024 |
| 1007 | Utah | 3rd | 1025 |
+------+--------+---------------------+------------+
我想在用户到达终点时提供响应
{
"country": "USA",
"listing": {
"Texas": {
"1st": {
"1054": "",
"1055": "",
},
"2nd": {
"1056": "",
"1057": "",
},
},
"Ohio": {
"1st": {
"3045": "",
"3128": "",
},
"2nd": {
"3046": ""
},
},
"Utah": {
"1st": {
"1023": "",
},
"2nd": {
"1024": ""
},
"3rd": {
"1025": ""
},
},
}
}
我选择了一个 Map 对象来生成最终结果。
@RequestMapping(path = "/getData/country", method = RequestMethod.GET)
public ResponseEntity<Map<String, Object>> retrieveData() {
Iterable<CountryModel> stud = myDataRepo.findAll();
Map<String, Object> parent = new HashMap<>();
parent.put("country", "USA");
stud.forEach(d -> {
String r = d.getYPROVINCEN();
Map<String, String> child = new HashMap<>();
child.put("name", d.getYDISTRICTN());
if (parent.containsKey(r)) {
List<Map<String, String>> children =
(List<Map<String, String>>) parent.get(r);
children.add(child);
} else {
List<Map<String, String>> children = new ArrayList<>();
children.add(child);
parent.put(r, children);
}
});
return ResponseEntity.ok().body(parent);
}
我的模特
@Entity
@Table(name = "Country")
public class CountryModel {
private String Province;
private String District;
private String Codes;
//getters and setters
我的仓库
@Repository
public interface MyDataRepo extends CrudRepository<CountryModel, String> {
}
从我上面的代码中,我只成功了一步并提取了省和地区
{
"country": "USA",
"Texas": [
{
"name": "1st"
},
{
"name": "2nd"
},
],
"Ohio": [
{
"name": "1st"
},
{
"name": "2nd"
},
],
"Utah": [
{
"name": "1st"
},
{
"name": "2nd"
},
{
"name": "3rd"
},
],
}
如何设置我的函数生成上面嵌套的JSON并获取代码、地区和省份?
【问题讨论】:
标签: java json spring-boot spring-data-jpa nativequery