2

Looking at this: http://jackson.codehaus.org/1.6.5/javadoc/org/codehaus/jackson/map/SerializationConfig.Feature.html

It looks like jackson json has a configuration in which only maps will have their null values serialized, but Gson only appears to have serialization of all null values, or none at all

sinneduy
  • 127
  • 6

2 Answers2

3
Gson gsonResponse = new GsonBuilder()
        .serializeNulls()
        .setPrettyPrinting()
        .create();

I think you might be looking for serializeNulls()

You may also create a customTypeAdapterFactory to handle class specific rendering.

Simpler use of TypeAdapterFactory

Community
  • 1
  • 1
dayv2005
  • 364
  • 4
  • 17
  • The primary use I was going for was for serialization of Null values to only occur for Maps. SerializeNulls() serializes null for everything – sinneduy Aug 06 '13 at 15:55
  • You can try to register a `JsonSerializer` on a `Map.class` and then use the code above inside the serializer – PomPom Aug 06 '13 at 18:36
2

This is the answer a friend helped me come up with (pretty much PomPom's answer):

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));
    }
}
sinneduy
  • 127
  • 6