Binary data as byte[]

2,545 views
Skip to first unread message

dmb

unread,
Nov 11, 2008, 4:59:25 PM11/11/08
to google-gson
In my application I often have opaque binary blobs of data that I want
to pass around via JSON. (Don't ask...) If I define byte[] members of
my classes, GSON happily converts my class instances to JSON and
things work swimmingly. However, the JSON representation of the byte
array is 5 times as big as the original, because GSON puts out a comma-
separated list of signed integers for the byte array.

What I'd like to do is, for type byte[] (or perhaps any slot with a
particular annotation) assume that the transmission channel is 8-bit
clean, and just output a string of the literal bytes. That way I would
have a little bit of overhead for such slots, but not the 4-5X I get
now.

If this possible? I looked at JsonSerializer but it wasn't obvious to
me that that would work for type byte[] -- in fact, it kind looked
like that approach wouldn't work.

Thanks.

Dave

BTW, GSON's cool. :)

inde...@gmail.com

unread,
Nov 11, 2008, 6:35:12 PM11/11/08
to google-gson
How about creating a custom serializer for the class containing byte[]
and then output whatever you want for byte[] field. You can use
Context.serialize to get default serialization of other members of the
class.



dmb

unread,
Nov 12, 2008, 7:43:49 AM11/12/08
to google-gson
That's a good suggestion; thanks. I actually started down that path
but wasn't sure how it would work in the context of many such classes.
For example, if I have 50 different classes like this, can I do what
you describe for a parent class, and then will GSON pick up the
inherited custom serialization from the superclass? (This is probably
a basic Java question; I admit I know C++ templates much better than
Java generics.)

Dave

Jacob Tomaw

unread,
Nov 12, 2008, 10:27:26 AM11/12/08
to googl...@googlegroups.com
GSON adapters do not match on subtypes (yet, I hope).  However, if all byte[]s in your models will be marshalled the same way, you can register an adapter for byte[].

Jacob
--
Jacob Tomaw
tfl:The Flatiron Life (http://tomaw.com)
Follow me on Twitter! (http://twitter.com/JacobTomaw)

dmb

unread,
Nov 13, 2008, 4:18:47 PM11/13/08
to google-gson
Cool; that will work for me. I was assuming you couldn't register a
custom serializer for base array types -- that actually works, huh?
Neat.

Dave

inde...@gmail.com

unread,
Nov 14, 2008, 6:59:02 PM11/14/08
to google-gson
I added tests for ensuring that custom serializer/deserializer work
for byte[] type.
See http://code.google.com/p/google-gson/source/detail?r=295

You can probably use that in your code too. Note that this test works
in the current version (1.2.3) in development. I am not sure if it
will work in 1.2.2 which is the public release. But 1.2.3 should be
out soon.
Reply all
Reply to author
Forward
0 new messages