【问题标题】:Does Gson have something like WRITE_NULL_MAP_VALUES (Jackson)?Gson 有类似 WRITE_NULL_MAP_VALUES (Jackson) 的东西吗?
【发布时间】:2013-08-05 16:46:53
【问题描述】:

看这个:http://jackson.codehaus.org/1.6.5/javadoc/org/codehaus/jackson/map/SerializationConfig.Feature.html

看起来 jackson json 有一个配置,其中只有映射将序列化其空值,但 Gson 似乎只对所有空值进行序列化,或者根本没有序列化

【问题讨论】:

    标签: java json jackson gson


    【解决方案1】:
    Gson gsonResponse = new GsonBuilder()
            .serializeNulls()
            .setPrettyPrinting()
            .create();
    

    我想你可能正在寻找 serializeNulls()

    您还可以创建一个 customTypeAdapterFactory 来处理特定于类的渲染。

    Simpler use of TypeAdapterFactory

    【讨论】:

    • 我打算的主要用途是仅对 Maps 进行 Null 值的序列化。 SerializeNulls() 为所有内容序列化 null
    • 您可以尝试在Map.class 上注册JsonSerializer,然后在序列化程序中使用上面的代码
    【解决方案2】:

    这是一个朋友帮我想出的答案(几乎是 PomPom 的答案):

    public static Gson createGson() {
        return new GsonBuilder().registerTypeAdapter(Map.class, new NullSerializingMapSerializer()).create();
    }
    
    public class NullSerializingMapSerializer implements JsonSerializer<Map> {
        private static final Gson gson = (new GsonBuilder()).serializeNulls().create();
        public JsonElement serialize(Map map, Type typeOfSrc, JsonSerializationContext context) {
            if(map == null) {
                return JsonNull.INSTANCE;
            }
            return new JsonPrimitive(gson.toJson(map));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 2014-09-22
      • 2010-11-29
      • 2020-03-26
      • 2011-10-18
      • 2023-03-09
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多