Gson HashMap Serialization <Teacher, List <Student >>

I have a map where the key value is a list of objects. I can serialize the keys through builder.enableComplexMapKeySerialization();, but the values ​​are not serialized as expected, because they return a string when deserializing instead of an object.

Below is the result of serialization

[{"id": 31001, "name": Teacher "]} // This is the key

[{"id": 33033, "name": "student1"}, {"id": 34001, "name": "student2"}]] // This is a list of values

I used the appropriate TypeToken, which is equal TypeToken<HashMap<Teacher, List<Student>>>, but at the same time, the values ​​of the list return a string when deserializing instead of an object.

+5
source share
1 answer

JSON consists of name / value pairs (where the side of the value can be a list of things). Part of the name of this is a string (see http://json.org )

What you are trying to do is use the object as a name; you cannot do it directly. A JSON object cannot be the name of a name / value pair.

If you read the documentation for enableComplexMapKeySerialization , it explains what the JSON result will be.

The generated JSON (map as a JSON array) will perfectly deserialize on your map. The following is a complete working example (Java 7).

, JSON Java, , . , equals() hashCode(), Teacher, Teacher ( ).

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class App 
{
    public static void main( String[] args )
    {
        HashMap<Teacher, List<Student>> map = new HashMap<>();
        Teacher t = new Teacher("12345", "Teacher");
        Teacher t2 = new Teacher("23456", "Teacher2");
        ArrayList<Student> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            list.add(new Student(String.valueOf(i), "Student" + String.valueOf(i)));
        }

        map.put(t, list);
        map.put(t2, list);

        GsonBuilder builder = new GsonBuilder();

        Gson gson =
            builder.enableComplexMapKeySerialization().setPrettyPrinting().create();
        Type type = new TypeToken<HashMap<Teacher,List<Student>>>(){}.getType();
        String json = gson.toJson(map, type);
        System.out.println(json);

        System.out.println("\nAfter deserialization:");
        HashMap<Teacher, List<Student>> map2 = gson.fromJson(json, type);

        for (Teacher t3 : map2.keySet()) {
            System.out.println(t3.name);
            for (Student s2 : map2.get(t3)) {
                System.out.println("\t" + s2.name);
            }
        }
    }
}

class Teacher {
    public String id;
    public String name;

    public Teacher(String id, String name) {
        this.id = id;
        this.name = name;
    }
}

class Student {
    public String id;
    public String name;

    public Student(String id, String name) {
        this.id = id;
        this.name = name;
    }

}

:

[
  [
    {
      "id": "12345",
      "name": "Teacher"
    },
    [
      {
        "id": "0",
        "name": "Student0"
      },
      {
        "id": "1",
        "name": "Student1"
      },
      {
        "id": "2",
        "name": "Student2"
      }
    ]
  ],
  [
    {
      "id": "23456",
      "name": "Teacher2"
    },
    [
      {
        "id": "0",
        "name": "Student0"
      },
      {
        "id": "1",
        "name": "Student1"
      },
      {
        "id": "2",
        "name": "Student2"
      }
    ]
  ]
]

After deserialization:
Teacher2
    Student0
    Student1
    Student2
Teacher
    Student0
    Student1
    Student2

equals() hashCode() Teacher, Teacher :

class Teacher {

    public String id;
    public String name;

    public Teacher(String id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public int hashCode()
    {
        int hash = 3;
        hash = 37 * hash + Objects.hashCode(this.id);
        hash = 37 * hash + Objects.hashCode(this.name);
        return hash;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (obj == null)
        {
            return false;
        }
        if (getClass() != obj.getClass())
        {
            return false;
        }
        final Teacher other = (Teacher) obj;
        if (!Objects.equals(this.id, other.id))
        {
            return false;
        }
        if (!Objects.equals(this.name, other.name))
        {
            return false;
        }
        return true;
    }

}

:

...
HashMap<Teacher, List<Student>> map2 = gson.fromJson(json, type);
Teacher t = new Teacher("23456", "Teacher2");
List<Student> list = map2.get(t);
...
+17

All Articles