Spring Boot to return JSON String from an external API

时间:2017-08-04 13:00:51

标签: json spring api spring-boot

I have a simple Spring boot project that uses controller mappings to get hard coded information from a class in my project.

For example, if I run the request : localhost:8080/topics, A JSON response is returned with the list of Topic Objects that i have previously created

I want to take this one step further and have a class who's variables are populated by calling this API and parsing the response :
https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo

I believe this can be done in Java by creating a HTTP connection and reading the data from an input stream, but is the an easier way of doing this with spring boot? Im not fully sure of the name of this procedure hence Im having trouble finding solutions online

2 个答案:

答案 0 :(得分:2)

由于您使用的是Spring Boot,因此使用Spring的RestTemplate是有道理的。它带有几个开箱即用的消息转换器,默认情况下使用Jackson作为json内容。

Spring发布了一个很好的Getting Started页面,用于使用RESTful Web服务。

但是,该服务返回的json内容看起来不会很好地映射到Java对象,因此您可能需要将其反序列化为HashMap以获取所需的数据。

答案 1 :(得分:0)

I did an attempt to create something like this.

https://github.com/StanislavLapitsky/SpringSOAProxy

The idea is to register controller interfaces. Each of the interfaces are mapped to some URL. For the interfaces a dynamic proxy are generated (if the implementations are not available locally). So developer just call controller's interface method. The method is invoked for dynamically generated proxy. The proxy uses RestTemplate to call remote URL. It sends and receive JSON and deserializes the returned JSOn to POJO objects returned from the controller.

You need to declare contract - controller interfaces plus DTO to exchange data as well as mapping to understand which URL should be called for each controller.