简体   繁体   English

如何在 Spring Boot 中读取具有给定 URL 的 JSON 文件?

[英]How to read a JSON file with a given URL in Spring Boot?

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?有人可以帮助我并告诉我如何在春季启动时从此 URL https://hccs-advancejava.s3.amazonaws.com/student_course.json读取 JSON 文件吗? Thanks!谢谢!

Its very simple ...它非常简单...

  1. Download the file as a string using some HttpClient class.使用某些 HttpClient 类将文件下载为字符串。 For example you can use RestTemplate例如,您可以使用 RestTemplate
  2. Parse the json to an object using the ObjectMapper class使用 ObjectMapper 类将 json 解析为对象

RestTemplate is available. RestTemplate可用。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM