2

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.