How to make nested json from single table

Viewed 30
+-----------+-----------+----------+
| 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.

1 Answers

I suppose you will get the data as a List from JPA. Then you could write a method (or use default jackson mapper) to convert that entity to a single json object.

Then use JSONArray from https://www.baeldung.com/java-org-json to append entities to this array.

Finally do a toString() and you will get the JSON result

Related