本文介绍了Spring Boot 从外部 API 返回 JSON 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 Spring Boot 项目,它使用控制器映射从我的项目中的类中获取硬编码信息.

例如,如果我运行请求:localhost:8080/topics,将返回一个 JSON 响应,其中包含我之前创建的主题对象列表

我想更进一步,让一个类通过调用这个 API 并解析响应来填充变量:
https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo

我相信这可以在 Java 中通过创建 HTTP 连接并从输入流中读取数据来完成,但使用 Spring Boot 是否更简单?我不完全确定此程序的名称,因此我无法在线找到解决方案

既然你使用的是 Spring Boot,那么利用 Spring 的 RestTemplate 是有道理的.它带有几个开箱即用的消息转换器,默认情况下使用 Jackson 来处理 json 内容.>

Spring 发布了一个很好的入门页面,用于使用 RESTful Web 服务.

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

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

解决方案

Since you are using Spring Boot, making use of Spring's RestTemplate makes sense. It comes with several message converters out of the box, and uses Jackson by default for json content.

Spring has published a good Getting Started page for consuming RESTful web services.

However, the json content returned by that services doesn't look like it will map well to a Java object, so you may have to deserialize it to a HashMap to get to the data you want.

这篇关于Spring Boot 从外部 API 返回 JSON 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:15