android Gson Serializing HashMap&lt;Teacher,List< Student>&gt;

cbwuti44  于 2023-11-15  发布在  Android
关注(0)|答案(1)|浏览(123)

我有一个Map,其中a键的值是一个对象列表。我能够通过builder.enableComplexMapKeySerialization();序列化键,但值没有按预期序列化,因为它们在序列化时返回字符串而不是对象。
下面是序列化的输出
[{“id”:31001,“name”:Teacher”]},//这是密钥
[{“id”:33033,“name”:“student 1”},{“id”:34001,“name”:“student 2”}]],//这是值列表
我使用了相关的TypeToken,它是TypeToken<HashMap<Teacher, List<Student>>>,但列表值仍然返回一个字符串,而不是对象。

0lvr5msh

0lvr5msh1#

JSON由名称/值对组成(其中值端可以是一个列表)。名称部分是字符串(参见:http://json.org
你要做的是使用一个对象作为名称;你不能直接这样做。JSON对象不能是名称/值对的名称。
如果你阅读了enableComplexMapKeySerialization的文档,它解释了最终的JSON是什么。
它生成的JSON(一个Map作为JSON数组)将完美地Map回你的map。下面是一个完整的工作示例(Java 7)。
请注意,一旦我从JSON转换回Java,我将迭代Map以获取键。这是因为如果Teacher中没有覆盖equals()hashCode(),则无法创建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


如果你在Teacher类中实现了equals()hashCode(),那么你就可以使用Teacher的一个新示例来从map中检索东西:

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

相关问题