开发者

Return a JSON response as CSV file from spring-boot controller

In my spring-boot project, I am fetching information from an external API in a JSON format. The response is represented as follows:

{
  "id":237,
  "first_name":"LeBron",
  "last_name":"James",
  "position":"F",
  "height_feet": 6,
开发者_Go百科  "height_inches": 8,
  "weight_pounds": 250,
  "team":{
      "id":14,
      "abbreviation":"LAL",
      "city":"Los Angeles",
      "conference":"West",
      "division":"Pacific",
      "full_name":"Los Angeles Lakers",
      "name":"Lakers"
  }
}

My task is to return a CSV file from this JSON response. I was looking for some info on the internet and only was able to find a conversion of a regular JSON to CSV, but the JSON response I am getting is nested and the conversion didn't work. How can I make it happen? What should I do? Any help will be appreciated.


One way to do this is to pre-process the JSON data and transform it into a flat JSON structure. You could write your own method to do this or you can use JOLT library to do this:

Sample spec

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "team": {
        "id": "team-id",
        "abbreviation": "team-abbreviation",
        "city": "team-city",
        "conference": "team-conference",
        "division": "team-division",
        "full_name": "team-full-name",
        "name": "team-name"
      }
    }
  }
]

Will transform the JSON to

{
  "id" : 237,
  "first_name" : "LeBron",
  "last_name" : "James",
  "position" : "F",
  "height_feet" : 6,
  "weight_pounds" : 250,
  "team-id" : 14,
  "team-abbreviation" : "LAL",
  "team-city" : "Los Angeles",
  "team-conference" : "West",
  "team-division" : "Pacific",
  "team-full-name" : "Los Angeles Lakers",
  "team-name" : "Lakers"
}

You can read more about JOLT here - https://github.com/bazaarvoice/jolt#Demo

You can also play around and test your spec live at the Demo page they have created at http://jolt-demo.appspot.com/#inception

Edit: After reading though the docs a bit more - here is a shorter version of the spec that will achieve similar result as the one given above:

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "team": {
        "*": "team-&"
      }
    }
  }
]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜