我正在尝试使用avro和架构序列化JSON。这不是一个rails应用程序(尽管标签,我需要注意),所以我也可以使用map,但是,以下工作都没有。
schema = { 'type' => 'record', 'name' => 'test', 'fields' => [ { 'name' => 'field_one', 'type' => 'string' },
{ 'name' => 'field_two', 'type' => 'string'},
{ 'name' => 'field_three', 'type' => 'string'},
{ 'name' => 'field_four', 'type' => 'string' } ] }.to_json
message = {'field_one' => 'why',
'field_two' => 'this',
'field_three' => 'no',
'field_four' => 'worky?'}.to_json
schema = Avro::Schema.parse(schema)
dw = Avro::IO::DatumWriter.new(schema)
buffer = StringIO.new()
encoder = Avro::IO::BinaryEncoder.new(buffer)
dw.write(message, encoder)
puts buffer.read
返回:'基准......不是模式的一个例子......'
使用以下内容替换上面的模式:
schema = { 'type' => 'map', 'values' => 'string' }.to_json
导致:'StringName'的未定义方法`键'
不确定,为什么我无法使用string创建一个简单的映射:string key:values。 Avro的ruby文档非常糟糕;很少的实际例子和很多占位符模板给想象留下了很多东西。我希望能够将此序列化字符串对象放入类型为application / json的http请求中,这可能是一个问题,因为avro想要成为二进制文件。
答案 0 :(得分:1)
require 'avro'
require 'json'
schema = { 'type' => 'record', 'name' => 'Test', 'fields' => [ { 'name' => 'field_one', 'type' => 'string' },
{ 'name' => 'field_two', 'type' => 'string'},
{ 'name' => 'field_three', 'type' => 'string'},
{ 'name' => 'field_four', 'type' => 'string' } ] }.to_json
message = {'field_one' => 'why',
'field_two' => 'this',
'field_three' => 'no',
'field_four' => 'worky?'}
schema = Avro::Schema.parse(schema)
writer = Avro::IO::DatumWriter.new(schema)
buffer = StringIO.new
writer = Avro::DataFile::Writer.new(buffer, writer, schema)
writer << message
writer.close # important
result = buffer.string
puts result