2014-09-11 56 views
0

使用Gson序列化Java对象列表时,我希望对象进行过滤,以便只有在状态字段中具有特定值的对象才被序列化。到目前为止,我想出了使用两个GSON情况下,一个具有自定义序列,一个没有停止Gson从序列化列表中的对象

... 
gson = gsonBuilder.create(); 

gsonBuilder.registerTypeAdapter(PropertyValue.class, new PropertyValueSerializer()); 
strictGson = gsonBuilder.create(); 

其中PropertyValueSerializer看起来是这样的:

public static class PropertyValueSerializer implements JsonSerializer<PropertyValue> { 
    @Override 
    public JsonElement serialize(PropertyValue propertyValue, Type typeOfT, JsonSerializationContext context) { 
     PropertyStatus propertyStatus = propertyValue.getStatus(); 
     if (propertyStatus == null || propertyStatus.isIndex()) { 
      return gson.toJsonTree(propertyValue); 
     } else { 
      return null; 
     } 
    } 
} 

也就是说,使用默认序列化或返回null状态字段指示PropertyValue不应被序列化。这会执行,但返回null显然不能从系列化排除对象的PropertyValue工作,我得到JSON这样的:

[ 

    { 
     "status": "HasDraft", 
     "sourceInfo": { 
      "author": "UUU", 
      "refId": "6aad7da8-e635-461d-8d42-c9a8aecd61fc" 
     }, 
     "valueType": "TEXT", 
     "value": { 
      "sv": "Rojo" 
     } 
    }, 
    null 
] 

有没有办法排除第二个对象的PropertyValue所以我得到

[ 

    { 
     "status": "HasDraft", 
     "sourceInfo": { 
      "author": "UUU", 
      "refId": "6aad7da8-e635-461d-8d42-c9a8aecd61fc" 
     }, 
     "valueType": "TEXT", 
     "value": { 
      "sv": "Rojo" 
     } 
    } 
] 

回答

0

回答我自己的问题,我发现如何去做。我需要一个List而不是PropertyValue的自定义序列化程序。在我使用默认序列之前过滤列表:

public static class PropertyValuesSerializer implements JsonSerializer<List<PropertyValue>> { 
    @Override 
    public JsonElement serialize(List<PropertyValue> propertyValues, Type typeOfT, JsonSerializationContext context) { 
     List<PropertyValue> filtered = new ArrayList<>(); 
     for (PropertyValue propertyValue : propertyValues) { 
      PropertyStatus propertyStatus = propertyValue.getStatus(); 
      if (propertyStatus == null || propertyStatus.isIndex()) { 
       filtered.add(propertyValue); 
      } 
     } 
     return gson.toJsonTree(filtered); 
    } 
} 
+1

“新的应用程序应该更喜欢TypeAdapter,其流API比这个接口的API树更有效。”您应该更好地使用TypeAdapters来提高效率。 – Devrim 2014-09-20 15:49:23

+0

谢谢爱琴海,将研究这一点,因为我还发现我的解决方案存在缺陷(处理递归结构)。 – 2014-09-21 18:54:15