Andy Chan Andy Chan - 5 months ago 16
JSON Question

java uses gson to parse from json format to map issues

I want to use google's gson to parse from json test to map, here is my code but get a exception:

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());


The json text is:

{
"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"
}
}


The error message is:

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

Answer

Your json text is invalid. String tokens inside Worker should be enclosed with json array []

"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"
]
Comments