Search code examples
javaserializationgson

How to de-serialize a Map<String, Object> with GSON


i am fairly new to GSON and get a JSON response of this format (just an easier example, so the values make no sense):

{
    "Thomas": {
        "age": 32,
        "surname": "Scott"
    },
    "Andy": {
        "age": 25,
        "surname": "Miller"
    }
}

I want GSON to make it a Map, PersonData is obviously an Object. The name string is the identifier for the PersonData.

As I said I am very new to GSON and only tried something like:

Gson gson = new Gson();
Map<String, PersonData> decoded = gson.fromJson(jsonString, new TypeToken<Map<String, PersonData>>(){}.getType());

but this threw the error:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 3141

Any help is appreciated :)


Solution

  • The following sample works for me

    static class PersonData {
        int age;
        String surname;
        public String toString() {
            return "[age = " + age + ", surname = " + surname + "]";
        }
    }
    
    public static void main(String[] args) {
        String json = "{\"Thomas\": {\"age\": 32,\"surname\": \"Scott\"},\"Andy\": {\"age\": 25,\"surname\": \"Miller\"}}";
        System.out.println(json);
        Gson gson = new Gson();
        Map<String, PersonData> decoded = gson.fromJson(json, new TypeToken<Map<String, PersonData>>(){}.getType());
        System.out.println(decoded);
    }
    

    and prints

    {"Thomas": {"age": 32,"surname": "Scott"},"Andy": {"age": 25,"surname": "Miller"}}
    {Thomas=[age = 32, surname = Scott], Andy=[age = 25, surname = Miller]}
    

    Likely your PersonData class is very different.