gpt4 book ai didi

java使用gson从json格式解析到 map 问题

转载 作者:行者123 更新时间:2023-12-01 21:25:43 25 4
gpt4 key购买 nike

我想使用谷歌的gson从json测试解析到 map ,这是我的代码,但出现异常:

Gson gson = new GsonBuilder().serializeNulls().setLenient().setPrettyPrinting().create();
Map<String, List<String>> map = new LinkedHashMap<>();
map = gson.fromJson("The json text", new TypeToken<Map<String, List<String>>>(){}.getType());

json 文本是:

{
"Worker": {
"127.0.0.1:9001",
"127.0.0.1:9002",
"127.0.0.1:9003",
"127.0.0.1:9004",
"127.0.0.1:9005",
"127.0.0.1:9006",
"127.0.0.1:9007"
}
}

错误信息是:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 2 column 16 path $.
at com.google.gson.Gson.fromJson(Gson.java:891)
at com.google.gson.Gson.fromJson(Gson.java:844)
at com.google.gson.Gson.fromJson(Gson.java:793)
at TestBasic.TestBasic.main(TestBasic.java:140)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 2 column 16 path $.
at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:351)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:187)
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:145)
at com.google.gson.Gson.fromJson(Gson.java:879)
... 3 more

最佳答案

您的 json 文本无效。 Worker 内的字符串标记应包含在 json 数组 []

"Worker": [
"127.0.0.1:9001",
"127.0.0.1:9002",
"127.0.0.1:9003",
"127.0.0.1:9004",
"127.0.0.1:9005",
"127.0.0.1:9006",
"127.0.0.1:9007"
]

关于java使用gson从json格式解析到 map 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38179332/

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