gpt4 book ai didi

java - 应为 BEGIN_OBJECT,但在 Gson 中为 STRING

转载 作者:行者123 更新时间:2023-12-01 19:59:52 28 4
gpt4 key购买 nike

嗨,我尝试通过 GSON 解析一些 JSON,它使用数字作为键。我引用了这篇文章,但它给出了一些错误,我不知道为什么。

How to convert json objects with number as field key in Java?

我也看到了这个帖子,但仍然无法解决我的问题。

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

enter image description here

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class Main {
public static void main(String[] args) {
Gson gson = new Gson();

Type type = new TypeToken<HashMap<String, HashMap<String, String>>>() {}.getType();
Map<String, Map<String, String>> map = gson.fromJson("./src/main/resources/input.json", type);

}
}

json文件是

{
"1":{"id":"1"}
}

最佳答案

fromJson 方法不接收文件名,它接收实际的 JSON:look at the docs here

但是有一个 overload而是接收一个 Reader:

try (FileReader reader = new FileReader("./src/main/resources/input.json"))
{
map = gson.fromJson(reader, type)
}
catch (...) { ... }

关于java - 应为 BEGIN_OBJECT,但在 Gson 中为 STRING,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48410320/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com