简体   繁体   English

gson 嵌套自定义序列化程序

[英]gson nested custom serializer

I've a nested object that I cannot manage to serialize with gson.我有一个无法使用 gson 序列化的嵌套对象。 I made a custom serializer which is used with the parent object but with the child one I didn't manage to make it work.我制作了一个自定义序列化程序,它与父对象一起使用,但与子对象一起使用,我没有设法让它工作。

So in my code below the custom serializer is used to serialize a Team .所以在我下面的代码中,自定义序列化器用于序列化Team That works.那个有效。 In this team I have a list of User that I want to serialize as well.在这个团队中,我还有一个我想序列化的User列表。 Unfortunately the method addProperty(String a, String b) askes for 2 strings (or a primitive) so I cannot add a property members which is of the class User .不幸的是,方法addProperty(String a, String b)要求 2 个字符串(或一个基元),因此我无法添加User类的属性成员。

Here is the code, first I create a Gson object and register the custom serializer for Team :这是代码,首先我创建一个Gson对象并为Team注册自定义序列化程序:

gson = new GsonBuilder().registerTypeAdapter(Team.class, new TeamSerializer())
            .create();
 gson.toJson(userData); // UserData instance.

This is the class that is gonna be serialized with the Gson object (I omitted irrelevant fields symbolized by //...):这是将要与Gson对象序列化的类(我省略了用 //... 符号化的不相关字段):

public class UserData{
    public Team team;
    //...
}

This is the custom serializer where I cannot add the property members :这是我无法添加属性members的自定义序列化程序:

public class TeamSerializer implements JsonSerializer<Team>{
    @Override
    public JsonElement serialize(Team src, Type type, JsonSerializationContext context) {
        JsonObject object = new JsonObject();
        object.addProperty("id", src.getIdteams());
        object.addProperty("name", src.getName());
        object.addProperty("tag", src.getTag());
        object.addProperty("picture", src.getProfilePic());
        //object.addProperty("members", src.getMembers());
        return object;
    }
}

This is the Team class:这是Team类:

public class Team implements Serializable {
    private long idteams;
    private String name;
    private String tag;
    private String profilePic;
    private List<User> members;
    //...
}

Describe the generic relationships with TypeToken and use the context to transform the list:描述与TypeToken的通用关系并使用上下文来转换列表:

TypeToken<List<User>> typeDescription = new TypeToken<List<User>>() {};
JsonElement members = context.serialize(src.getMembers(), typeDescription.getType());
object.add("members", members);

If User isn't a standard bean you may need a TypeAdapter for it too.如果User不是标准 bean,您可能也需要一个TypeAdapter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM