有没有一种方法可以在Rust中使用avro-rs序列化JSON值?

时间:2020-07-06 14:24:54

标签: rust avro

我想使用avro-rs序列化JSON值。我似乎找不到解决方法。要进行复制,您可以执行以下操作:

  1. 通过运行cargo new example
  2. 创建一个新项目
  3. 使用以下依赖项更新Cargo.toml
[package]
name = "rust-example"
version = "0.1.0"
edition = "2018"

[dependencies]
serde_json = "1.0.52"
avro-rs = "0.10.0"
  1. 使用以下命令更新scr/main.rs
use avro_rs::{Schema, Writer};
use serde_json::json;

fn main() {
    let raw_schema = r#"
        {
            "type": "record",
            "name": "action",
            "fields": [
                {"name": "id", "type": "string"}
            ]
        }
    "#;

    let schema = Schema::parse_str(raw_schema).unwrap();

    let mut writer = Writer::new(&schema, Vec::new());

    let action = json!({
        "id": "some id"
    });

    writer.append(action).unwrap(); // panics: ValidationError("value does not match schema")
}
  1. 最后运行cargo run来查看输出。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用avrow条板箱。它具有from_json类型的Record API:https://docs.rs/avrow/0.2.0/avrow/struct.Record.html#method.from_json

检查存储库中的json example