[英]How to make nested json from single table
+-----------+-----------+----------+
| Year | Type | Count |
+-----------+-----------+----------+
| 2020 | Motor | 12 |
| 2020 | Nut | 35 |
| 2020 | Bolt | 47 |
| 2020 | Engine | 78 |
| 2020 | Oil | 125 |
| 2020 | Filter | 5 |
| 2020 | AC | 10 |
| 2021 | Motor | 22 |
| 2021 | Nut | 76 |
| 2021 | Bolt | 2 |
| 2021 | Engine | 5 |
| 2021 | Oil | 6 |
| 2021 | Filter | 6 |
| 2021 | AC | 12 |
+-----------+-----------+----------+
Above is the data table consists of year, type & its count.以上是数据表,包括年份、类型及其计数。
[
{
"year": 2021,
"Motor": [
{
"count": 22
}
]
},
{
"year": 2021,
"Nut": [
{
"count": 76
}
]
},
{
"year": 2021,
"Bolt": [
{
"count": 2
}
]
},
{
"year": 2021,
"Engine": [
{
"count": 5
}
]
},
{
"year": 2021,
"Oil": [
{
"count": 6
}
]
},
{
"year": 2021,
"Filter": [
{
"count": 6
}
]
},
{
"year": 2021,
"AC": [
{
"count": 12
}
]
},
{
"year": 2020,
"Motor": [
{
"count": 12
}
]
},
{
"year": 2020,
"Nut": [
{
"count": 35
}
]
},
{
"year": 2020,
"Bolt": [
{
"count": 47
}
]
},
{
"year": 2020,
"Engine": [
{
"count": 18
}
]
},
{
"year": 2020,
"Oil": [
{
"count": 125
}
]
},
{
"year": 2020,
"Filter": [
{
"count": 5
}
]
},
{
"year": 2020,
"AC": [
{
"count": 10
}
]
}
]
Looking to get the JSON response as above.希望得到 JSON 响应,如上。
I suppose you will get the data as a List from JPA.我想你会从 JPA 中获取数据作为列表。 Then you could write a method (or use default jackson mapper) to convert that entity to a single json object.
然后您可以编写一个方法(或使用默认的 jackson 映射器)将该实体转换为单个 json object。
Then use JSONArray
from https://www.baeldung.com/java-org-json to append entities to this array.然后使用
JSONArray
从https://www.baeldung.com/java-org-json到 append 实体到这个数组。
Finally do a toString() and you will get the JSON result最后做一个 toString() 你会得到 JSON 结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.