Java gson, ClassCastException on decoding to Map<String,String[]>

别来无恙 提交于 2021-01-04 09:15:23

问题


I want to decode a json string like {"username":["emmet"]} to a Map<String,String[]> object.

using following code:

    String json = "{\"username\":[\"emmet\"]}";
    Gson gson = new GsonBuilder().create();
    Map<String,String[]> map = new HashMap<>();
    map  = (Map<String,String[]>)gson.fromJson(json, map.getClass());
    String[] val = map.get("username");
    System.out.println(val);

this exception occurs:

Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to [Ljava.lang.String;
    at com.company.Main.main(Main.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Gson has decoded my object as a Map<String, ArrayList<String>> object instead of Map<String,String[]> object. How can I force gson to decode my object as Array not ArrayList?

I'm using gson-2.8.1.


回答1:


Gson converts json array to a java List, so when you trying to get the usernames as String[] you getting an ClassCastException

If you want to get it as a String[] use it that way :

    String json = "{\"username\":[\"emmet\"]}";
    Gson gson = new GsonBuilder().create();
    Map<String,List<String>> map = new HashMap<>();
    map  = (Map<String,List<String>>)gson.fromJson(json, map.getClass());
    List<String> usernames = map.get("username");
    String[] val = usernames.toArray(new String[0]);
    System.out.println(val);

That will work for you




回答2:


You can parse everything out and place it into a Map manually. Here is some code that demonstrates how you could do this

String jsonString = "{\"username\":[\"emmet\"]}";
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject();
Set<String> keys = jsonObject.keySet();
Map<String, String[]> map = new HashMap<>();
for(String key:keys){
    JsonElement jsonElement = jsonObject.get(key);
    if(jsonElement.isJsonArray()){
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        String[] strings = new String[jsonArray.size()];
        for(int i = 0; i < jsonArray.size(); i++){
            strings[i] = jsonArray.get(i).getAsString();
        }
        map.put(key, strings);
    } else {
        //Handle other instances such as JsonObject, JsonNull, and JsonPrimitive
    }
}


来源:https://stackoverflow.com/questions/47889531/java-gson-classcastexception-on-decoding-to-mapstring-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!