GSON-特定情况下的自定义序列化程序

斯特凡·皮耶特(StéphanePiette):

我有这个架构:

public class Student {
       public String name;
       public School school;
}

public class School {
       public int id;
       public String name;
}
public class Data {
      public ArrayList<Student> students;
      public ArrayList<School> schools;
}

我想用Gson序列化Data对象,并得到类似的东西:

{ "students": [{ 
                 "name":"name1",
                 "school": "1"          //the id of the scool, not its entire Json
              }],
  "school": [{                        //the entire JSON
              "id" : "1",
              "name": "schoolName"
            }]
}

为此,我必须对学生部分使用自定义序列化程序,以便Gson仅打印学校的ID。但是对于学校来说,我必须有正常的序列化器。

我如何只用一个Gson对象就能完成所有工作?

乔纳斯:

您可以编写自定义序列化器,如下所示:

public class StudentAdapter implements JsonSerializer<Student> {

 @Override
 public JsonElement serialize(Student src, Type typeOfSrc,
            JsonSerializationContext context) {

        JsonObject obj = new JsonObject();
        obj.addProperty("name", src.name);
        obj.addProperty("school", src.school.id);

        return obj;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章