【问题标题】:Ruby Avro: Record schema reports datum is not validRuby Avro:记录模式报告数据无效
【发布时间】:2018-06-14 00:38:49
【问题描述】:

我正在尝试使用 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

导致:'未定义的方法 `keys' for StringObject'

不确定,为什么我不能用 string:string key:values 创建一个简单的地图。 Avro 的 ruby​​ 文档很糟糕。非常少的实际示例和大量的占位符模板,这给我们留下了很多想象空间。我希望能够将此序列化的字符串对象放入类型为 application/json 的 http 请求中,这可能是一个问题,因为 avro 想要二进制。

【问题讨论】:

  • 不确定是否有错字,但message 未设置,json_hash 从未使用过。
  • 唉,我无法向你隐瞒我的缺点......

标签: ruby-on-rails json ruby serialization avro


【解决方案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

【讨论】:

  • 你愿意嫁给我吗?有一个有用的 ruby​​ 编码器在家里帮忙会很方便。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多