Home > Net >  How to read a JSON file with a given URL in Spring Boot?
How to read a JSON file with a given URL in Spring Boot?

Time:11-07

Can some please help me and show me how to read a JSON file from this URL https://hccs-advancejava.s3.amazonaws.com/student_course.json in spring boot? Thanks!

CodePudding user response:

Its very simple ...

  1. Download the file as a string using some HttpClient class. For example you can use RestTemplate
  2. Parse the json to an object using the ObjectMapper class

CodePudding user response:

RestTemplate is available.

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class MyController {

    private final RestTemplate restTemplate;

    public MyController(final RestTemplateBuilder builder) {
        this.restTemplate = builder.build();
    }

    @GetMapping
    public List<Map<String, ?>> index() throws URISyntaxException {
        final URI url = new URI("https://hccs-advancejava.s3.amazonaws.com/student_course.json");
        final ResponseEntity<List> resp = restTemplate.getForEntity(url, List.class);
        final List<Map<String, ?>> list = resp.getBody();
        return list;
    }
}
  • Related