Java gson,ClassCastException解码为Map <string,string []>

时间:2017-12-19 14:51:03

标签: java json gson

我想将{"username":["emmet"]}之类的json字符串解码为Map<String,String[]>对象。

使用以下代码:

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

发生此异常:

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将我的对象解码为Map<String, ArrayList<String>>对象而不是Map<String,String[]>对象。如何强制gson将我的对象解码为Array而非ArrayList

我正在使用gson-2.8.1

2 个答案:

答案 0 :(得分:3)

Gsonjson数组转换为java List,因此当您尝试将用户名设为String[]时,您会获得ClassCastException

如果你想以String[]的方式使用它:

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

这对你有用

答案 1 :(得分:-1)

您可以解析所有内容并手动将其放入地图中。以下是一些演示如何执行此操作的代码

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