Gson deserialization of List into realmList

前端 未结 4 612
刺人心
刺人心 2020-12-01 05:18

I\'m using retrofit with gson to deserialize my json into realm objects. This works very well for the most part. Trouble arises when dealing with

Rea

4条回答
  •  感动是毒
    2020-12-01 06:07

    It is better to use JsonSerializer and JsonDeserializer rather than TypeAdapter for your RealmObject, because of 2 reasons:

    1. They allow you to delegate (de)serialization for your RealmObject to the default Gson (de)serializer, which means you don't need to write the boilerplate yourself.

    2. There's a weird bug in Gson 2.3.1 that might cause a StackOverflowError during deserialization (I tried the TypeAdapter approach myself and encountered this bug).

    Here's how (replace Tag with your RealmObject class):

    (NOTE that context.serialize and context.deserialize below are equivalent to gson.toJson and gson.fromJson, which means we don't need to parse the Tag class ourselves.)

    Parser + serializer for RealmList:

    public class TagRealmListConverter implements JsonSerializer>,
            JsonDeserializer> {
    
        @Override
        public JsonElement serialize(RealmList src, Type typeOfSrc,
                                     JsonSerializationContext context) {
            JsonArray ja = new JsonArray();
            for (Tag tag : src) {
                ja.add(context.serialize(tag));
            }
            return ja;
        }
    
        @Override
        public RealmList deserialize(JsonElement json, Type typeOfT,
                                          JsonDeserializationContext context)
                throws JsonParseException {
            RealmList tags = new RealmList<>();
            JsonArray ja = json.getAsJsonArray();
            for (JsonElement je : ja) {
                tags.add((Tag) context.deserialize(je, Tag.class));
            }
            return tags;
        }
    
    }
    

    Tag class:

    @RealmClass
    public class Tag extends RealmObject {
        private String value;
    
        public String getValue() {
            return value;
        }
    
        public void setValue(String value) {
            this.value = value;
        }
    }
    

    Then register your converter class with Gson:

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(new TypeToken>() {}.getType(),
                    new TagRealmListConverter())
            .create();
    

提交回复
热议问题