简体   繁体   English

如何根据 GSON 的某些值从序列化中排除对象?

[英]How to exclude objects from serializing based on some values witg GSON?

I have a json structure to make from a POJO class like this -我有一个 json 结构,可以像这样从 POJO class 制作 -

 {
"arrayA":[
      {
         "arrayB":[
            {
              "arrayC":[
                  {
                     "base64String":null
                  },
                  {
                     "base64String":"base 64 value here"
                  }
               ]
            }
         ]
      }
   ]
}

As you can see, Objects in arrayC have a field named base64String.如您所见,arrayC 中的对象有一个名为 base64String 的字段。 Now this base64String may be null sometimes, so while serializing the POJO to json, is there a way to check if this base64String is null and omit that particular object from serializing? Now this base64String may be null sometimes, so while serializing the POJO to json, is there a way to check if this base64String is null and omit that particular object from serializing?

Looking at the documentation I was able to do it myself.查看文档,我可以自己完成。 Answering here if someone else needs this.如果其他人需要这个,请在这里回答。 We need to use JsonSerializer provided by Gson to check for values as they are being serialized.我们需要使用JsonSerializer提供的 JsonSerializer 来检查正在序列化的值。

    public class SerializeFiles implements JsonSerializer<MyClass> {

    @Override
    public JsonElement serialize(MyClass src, Type typeOfSrc, JsonSerializationContext context) {
        Gson gson = new Gson();
        JsonObject object = (JsonObject) gson.toJsonTree(src);
        JsonArray arrayA = object.getAsJsonArray("arrayA");
        for (JsonElement element : arrayA) {
            JsonObject objA = element.getAsJsonObject();
            JsonArray arrayB = insObj.getAsJsonArray("arrayB");
            for (JsonElement elementB : arrayB) {
                JsonObject objB = elementB.getAsJsonObject();
                JsonArray arrayC = objB.getAsJsonArray("arrayC");
                for(JsonElement elementC : arrayC) {
                    JsonObject objectC = elementC.getAsJsonObject();
                    if(objectC.get("base64String") == null) {
                        arrayC.remove(objB);
                    }
                }
            }
            return object;
        }
    }

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

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