forcing null into json object

1,244 views
Skip to first unread message

Omar Khan

unread,
Jul 24, 2008, 9:30:39 PM7/24/08
to google-gson
hi all,

i'm creating a json object using addProperty and add calls on a
JsonObject. one thing i want to add is that a key/value pair that is
"value : null" .. when i do an add("value", null) that succeeds, but
the serialized data doesn't seem to contain the mapping.

let me know what you suggest.

omar

Inderjeet Singh

unread,
Jul 25, 2008, 12:48:35 AM7/25/08
to googl...@googlegroups.com
That behavior of Gson is by design. On deserialization, Gson will set
the equivalent field in the Java object to null.

What are you trying to do? Why do you care to have the null mapping preserved?

Inder

Chris Lambert

unread,
Jul 28, 2008, 4:31:31 PM7/28/08
to google-gson
I separately ran into this issue when trying to code to a pre-existing
spec. The client only accepted explicit nulls, so I had to manually
override GSON's output in that specific case. I'm not sure how common
it is, but it might be worth supporting a verbosity mode for select
serializations. Thoughts?

- Chris

On Jul 24, 9:48 pm, "Inderjeet Singh" <inder...@gmail.com> wrote:
> That behavior of Gson is by design. On deserialization, Gson will set
> the equivalent field in the Java object to null.
>
> What are you trying to do? Why do you care to have the null mapping preserved?
>
> Inder
>

Inderjeet Singh

unread,
Jul 28, 2008, 5:13:34 PM7/28/08
to googl...@googlegroups.com
Ok, so seems like this has wider use, so is probably worth exposing
through a GsonBuilder setting.

So, here is a design that I can think of:

add a new method in GsonBuilder, enableSerializationOfNulls (feel free
to suggest an alternate name).

Calling this method will serialize all null fields.

This design has the drawback that you can not apply this logic
selectively. Will that be an issue? Would you rather have an
annotation that specified whether to serialize a specific field even
if it is null?

Eric Muntz

unread,
Jul 29, 2008, 8:25:01 AM7/29/08
to googl...@googlegroups.com
The annotation would be nice, but an alternative would be needed when
you don't have access to the code. Is there a way this could be
accomplished with a JsonSerializer? Could we use
JsonObject.addProperty(String, JsonElement) with null for JsonElement
and have it serialized as null? Would it be more clear to build a
JsonNull subclass of JsonElement?

-Eric

Inderjeet Singh

unread,
Jul 30, 2008, 9:55:38 PM7/30/08
to googl...@googlegroups.com
That is a good idea and I have now implemented it in revision 126
available at http://code.google.com/p/google-gson/source/detail?r=126

GsonBuilder now has an option serializeNulls() that causes all null
values to be serialized.
There is also a new class JsonNull that can be used by custom
serializers to indicate null values.

Can someone look at the change and provide comments on whether this is
good enough?

Reply all
Reply to author
Forward
0 new messages