首页 > 解决方案 > 使用 Spring Boot 使用 JSON 数据

问题描述

我正在关注关于使用 Spring Boot 1 [使用 RESTful Web 服务] 的 spring.io 教程。

在本教程中,它提供了一个包含以下 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,所以我可能会遗漏一些非常简单的东西。

请让我知道是否有任何我可以添加的内容。

感谢您的时间。

标签: javaspringspring-boot

解决方案


如果您的数据不是常量,那么您可以以 JSON 对象或字符串的形式使用它,而不是直接映射到任何 Class 类型对象

接受为字符串

@PostMapping("/getData")
    public List<DataList> getDataList(@RequestBody String request) {
}

接受为 JSON 对象

@PostMapping("/getData")
    public List<DataList> getDataList(@RequestBody JSONObject content)
            {
}

一旦得到 String ,它就可以转换为JSON Object

JSONOBject reqObj = new JSONObject(request);

然后使用JSONObject 的 get 方法来获取任何属性

String field1 = reqObj.get("fieldName");

推荐阅读