Skip to content

Instantly share code, notes, and snippets.

@frsyuki
Created August 13, 2011 15:01
Show Gist options
  • Save frsyuki/1143931 to your computer and use it in GitHub Desktop.
Save frsyuki/1143931 to your computer and use it in GitHub Desktop.
require 'java'
require 'msgpack-0.6.0-devel.jar'
##
# Serialize
#
gzout = java.io.ByteArrayOutputStream.new
out = java.util.zip.GZIPOutputStream.new(gzout)
m = org.msgpack.MessagePack.new
pk = m.createPacker(out)
pk.writeArrayBegin(2)
# 100
pk.writeInt(100)
# {"array"=>[1,2,3]}
pk.writeMapBegin(1)
pk.writeString("array")
pk.writeArrayBegin(3)
pk.writeInt(1)
pk.writeInt(2)
pk.writeInt(3)
pk.writeArrayEnd()
pk.writeMapEnd()
pk.writeArrayEnd()
# or ...
pk.write [200, "str"]
out.close
bytes = gzout.toByteArray
##
# Deserialize
#
input = java.util.zip.GZIPInputStream.new(java.io.ByteArrayInputStream.new bytes)
m = org.msgpack.MessagePack.new
u = m.createUnpacker(input)
tsv = ''
u.each {|arr|
tsv << arr.collect {|e|
if e.is_a?(org.msgpack.type.RawValue)
e.getString
else
e.toString
end
}.join("\t") << "\n"
}
puts tsv
# 100 {"array":[1,2,3]}
# 200 str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment