我将继续学习spring.io教程,了解如何通过Spring Boot 1使用RESTful web服务。
在本教程中,它提供了一个包含以下JSON数据的示例:
{
type: "success",
value: {
id: 10,
quote: "Really loving Spring Boot, makes stand alone Spring apps easy."
}
}然后,它提供以下类:
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
@Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}并声明“要将数据直接绑定到自定义类型,需要指定与API返回的JSON文档中的键完全相同的变量名”。
我尝试拉取的JSON数据格式如下:
{
"Meta Data": {
"1. Information": "Daily Prices (open, high, low, close) and Volumes",
"2. Symbol": "IBM",
"3. Last Refreshed": "2020-05-08",
"4. Output Size": "Compact",
"5. Time Zone": "US/Eastern"
},"Time Series (Daily)": {
"2020-05-08": {
"1. open": "122.6700",
"2. high": "123.2300",
"3. low": "121.0600",
"4. close": "122.9900",
"5. volume": "5002450"
},
"2020-05-07": {
"1. open": "122.9800",
"2. high": "123.2600",
"3. low": "120.8500",
"4. close": "121.2300",
"5. volume": "4412047"
}
}我的问题是,如果数据不是常量,我如何在类中设置get和set方法?同样,本教程声明“您需要指定与API返回的JSON文档中的键完全相同的变量名”。
如果这让人困惑,我很抱歉。我还在学习Spring Boot,所以我可能会错过一些非常容易的东西。
如果有什么需要我补充的,请告诉我。
谢谢您抽时间见我。
发布于 2020-05-11 22:27:21
如果您的数据不是常量,那么您可以使用JSON对象或字符串的形式,而不是直接映射到任何类类型对象
接受为字符串的
@PostMapping("/getData")
public List<DataList> getDataList(@RequestBody String request) {
}作为JSON对象接受
@PostMapping("/getData")
public List<DataList> getDataList(@RequestBody JSONObject content)
{
}一旦获得字符串,就可以将其转换为JSON Object。
JSONOBject reqObj = new JSONObject(request);然后使用JSONObject的get方法来获取任意属性
String field1 = reqObj.get("fieldName");发布于 2020-05-11 23:12:52
您可以尝试将map与@RequestBody一起使用,如下所示:
@RestController
public class Controller {
@PostMapping
public void postWithMap(@RequestBody Map<String, Object> requestMap) {
// do something with the map..
}
}但如果可能,我会尝试修改请求,以便使用时间序列的集合,如下所示:
{
"Meta Data": {
"Information": "Daily Prices (open, high, low, close) and Volumes",
"Symbol": "IBM",
"Last Refreshed": "2020-05-08",
"Output Size": "Compact",
"Time Zone": "US/Eastern"
},
"Time Series (Daily)": [
{
"date": "2020-05-08",
"open": "122.6700",
"high": "123.2300",
"low": "121.0600",
"close": "122.9900",
"volume": "5002450"
},
{
"date": "2020-05-07",
"open": "122.9800",
"high": "123.2600",
"low": "120.8500",
"close": "121.2300",
"volume": "4412047"
}
]
}https://stackoverflow.com/questions/61731716
复制相似问题