为了账号安全,请及时绑定邮箱和手机立即绑定

使用 GSON 将 JSON 转换为 Java 类

使用 GSON 将 JSON 转换为 Java 类

隔江千里 2023-12-30 15:31:47
我正在尝试将以下 API 数据转换为 java 类。我特别感兴趣的是选择带有日期键的 timeSeriesDaily 字段和 openingStockPrice 字段。我尝试使用以下数据结构来捕获相关字段public class AlphavantageData {    List<Map<String,TimeSeriesDaily>> timeSeriesDaily;    public List<Map<String, TimeSeriesDaily>> getTimeSeriesDaily() {        return timeSeriesDaily;    }    public void setTimeSeriesDaily(List<Map<String, TimeSeriesDaily>> timeSeriesDaily) {        this.timeSeriesDaily = timeSeriesDaily;    }}public class TimeSeriesDaily {    private Map<String,DayCloseStockPrice> dayStockPriceRecords;    public Map<String, DayCloseStockPrice> getDayStockPriceRecords() {        return dayStockPriceRecords;    }    public void setDayStockPriceRecords(Map<String, DayCloseStockPrice> dayStockPriceRecords) {        this.dayStockPriceRecords = dayStockPriceRecords;    }}public class DayCloseStockPrice {    private String closingStockPrice;    public String getClosingStockPrice() {        return closingStockPrice;    }    public void setClosingStockPrice(String closingStockPrice) {        this.closingStockPrice = closingStockPrice;    }}但是我不断收到以下 GSON 错误:java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 10 column 10 path $.timeSeriesDaily[0]如果有人能回答为什么这不起作用以及如何解决它,我将不胜感激。
查看完整描述

2 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

确保您的 json 对象格式正确并且与 POJO 兼容,稍后您可以使用下面的代码进行不同类型的转换 -


 Gson gson = new Gson();

// 1. JSON file to Java object

Staff staff = gson.fromJson(new FileReader("C:\\projects\\test.json"), Test.class);


// 2. JSON string to Java object

String json = "{'name' : 'test'}";

Staff staff = gson.fromJson(json, Test.class);


// 3. JSON file to JsonElement ->  String

JsonElement json = gson.fromJson(new FileReader("C:\\projects\\test.json"), JsonElement.class);

String result = gson.toJson(json);

Maven 依赖 -


<dependency>

    <groupId>com.google.code.gson</groupId>

    <artifactId>gson</artifactId>

    <version>x.x.x</version>

</dependency>


查看完整回答
反对 回复 2023-12-30
?
茅侃侃

TA贡献1842条经验 获得超21个赞

你的 json 结构不正确,但是我已经在你的类中尝试了以下 json 并且它有效


{

    "Meta Data": {

        "1. Information": "Daily Time Series with Splits and Dividend Events",

        "2. Symbol": "MSFT",

        "3. Last Refreshed": "2019-10-24",

        "4. Output Size": "Compact",

        "5. Time Zone": "US/Eastern"

    },

    "timeSeriesDaily": [

        {

            "2019-10-24": {

                "1. open": "139.3900",

                "2. high": "140.4100",

                "3. low": "138.6700",

                "closingStockPrice": "139.9400",

                "5. adjusted close": "139.9400",

                "6. volume": "34434281",

                "7. dividend amount": "0.0000",

                "8. split coefficient": "1.0000"

            }

        }

    ]

}


查看完整回答
反对 回复 2023-12-30
  • 2 回答
  • 0 关注
  • 124 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信