【问题标题】:How to access third party API data in Java Spring BootJava Spring Boot中如何访问第三方API数据
【发布时间】:2023-02-06 02:20:27
【问题描述】:

我想问一下如何访问 json ("latitude", "latitude") 中的字段才能在浏览器中将它们显示为字符串。

@RestController
@RequestMapping("/api/v1/")
public class ISSTrackerController {

    @GetMapping("/location")
    public ResponseEntity<String> getISSLocation() {
        String uri = "http://api.open-notify.org/iss-now.json";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(uri, String.class);

        return new ResponseEntity<>(result, HttpStatus.OK);
    }
}

【问题讨论】:

  • String 而不是 result 应该是一个表示调用该端点的返回 JSON 结构的类(或特定于应用程序的 DTO,以避免端点响应泄漏)。此外,RestTemplate 是线程安全且可注入的,因此不需要创建新实例。

标签: java json spring-boot http spring-mvc


【解决方案1】:

要从 java 中的响应中获取数据,您需要创建一些 POJO 来获取响应:

class IssPosition {
    private Double latitude;
    private Double longitude;

    // getters & setters
}

class IssResponse {
    // Here the iss_position property in hte response is in cammel case,
    // with the @JsonProperty annotation we tell the parser to pass that 
    // property to the annotated field issPosition
    @JsonProperty("iss_position")
    private IssPosition issPosition;
    private String message;
    private Timestamp timestamp;

    // getters & setters
}

然后你可以拨打RestTemplate

@RestController
@RequestMapping("/api/v1/")
public class ISSTrackerController {

    @GetMapping("/location")
    public ResponseEntity<String> getISSLocation() {
        String uri = "http://api.open-notify.org/iss-now.json";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<IssResponse> response = restTemplate.getForObject(uri, IssResponse.class);
        // We get te response as an IssResponse object
        IssResponse result = response.getBody();
        // We get the iss_position property so you have access 
        // to the latitude and longitude fields by
        IssPosition position = result.getIssPosition();
        // You can just return the position so you have a json like this one: 
        // { "latitude": "-24.0470", "longitude": "64.0261" }
        return new ResponseEntity<>(position, HttpStatus.OK);
    }
}

附言: 编辑答案以使用来自 RestTemplate 调用的 ResponseEntity 中包装的实际响应。 感谢@OneCricketeer 指出这一点!!!

【讨论】:

  • 你想要ResponseEntity&lt;IssPosition&gt;吗?
  • 多谢!有效。只有在方法类型中应该是 <IssPosition> 而不是 <String>,但我处理了那个。再次感谢
【解决方案2】:
@GetMapping("/location")
private String getISSLocation()
{
    String url = "http://api.open-notify.org/iss-now.json";
    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(url, String.class);
    return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多