user6618310
user6618310

Reputation: 39

how to parse JSON file using rest API and spring boot

I'm new to this, and I want to read JSON file imported with rest api and parse it with spring boot. I worked with CSV file with his method :

 @RequestMapping(value = "/import", method = RequestMethod.POST)
      public String handleFileUpload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
          String name = multipartFile.getOriginalFilename();
          System.out.println("File name: "+name);
          byte[] bytes = multipartFile.getBytes();
          System.out.println("File uploaded content:\n" + new String(bytes));
          return "file uploaded";
      }

Now i want to parse a JSON File :

[  
    {  
        "name":"John",
        "city":"Berlin",
        "cars":[  
            "audi",
            "bmw"
        ],
        "job":"Teacher"
    },
    {  
        "name":"Mark",
        "city":"Oslo",
        "cars":[  
            "VW",
            "Toyata"
        ],
        "job":"Doctor"
    }
]

I have try it to parse this file with java and it works for me but I dont know how to get it with rest api

This method to parse te file JSON and it works

public static void main(String[] args) throws FileNotFoundException,
    IOException, ParseException {

JSONParser parser = new JSONParser();
JSONArray jsonArray = (JSONArray) parser.parse(new FileReader(
        "D:/PFE 2018/testjsonfile.json"));

for (Object o : jsonArray) {
    JSONObject person = (JSONObject) o;

    String strName = (String) person.get("name");
    System.out.println("Name::::" + strName);

    String strCity = (String) person.get("city");
    System.out.println("City::::" + strCity);

    JSONArray arrays = (JSONArray) person.get("cars");
    for (Object object : arrays) {
        System.out.println("cars::::" + object);
    }
    String strJob = (String) person.get("job");
    System.out.println("Job::::" + strJob);
    System.out.println();

}

}

now how to reuse this methode with rest api

Upvotes: 0

Views: 9721

Answers (1)

AR1
AR1

Reputation: 5003

It depends what you want to do with your JSON (it's not entirely clear in your question). In general, good practice with Spring Boot is to use Jackson either:

  • binding your JSON with a POJO if you expect your JSON to have a known format or

  • mapping your JSON in a tree.

Examples for the described behaviours can be found in this article for instance.

Upvotes: 1

Related Questions