简体   繁体   English

使用手动实现的 Serialize 序列化到 TOML 时,为什么会出现 UnsupportedType 错误?

[英]Why do I get an UnsupportedType error when serializing to TOML with a manually implemented Serialize for an enum with struct variants?

I'm trying to implement Serialize for an enum that includes struct variants.我正在尝试为包含结构变体的枚举实现Serialize The serde.rs documentation indicates the following: serde.rs 文档指出以下内容:

enum E {
    // Use three-step process:
    //   1. serialize_struct_variant
    //   2. serialize_field
    //   3. end
    Color { r: u8, g: u8, b: u8 },

    // Use three-step process:
    //   1. serialize_tuple_variant
    //   2. serialize_field
    //   3. end
    Point2D(f64, f64),

    // Use serialize_newtype_variant.
    Inches(u64),

    // Use serialize_unit_variant.
    Instance,
}

With that in mind, I proceeded to implemention:考虑到这一点,我开始实施:

use serde::ser::{Serialize, SerializeStructVariant, Serializer};
use serde_derive::Deserialize;

#[derive(Deserialize)]
enum Variants {
    VariantA,
    VariantB { k: u32, p: f64 },
}

impl Serialize for Variants {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            Variants::VariantA => serializer.serialize_unit_variant("Variants", 0, "VariantA"),
            Variants::VariantB { ref k, ref p } => {
                let mut state =
                    serializer.serialize_struct_variant("Variants", 1, "VariantB", 2)?;
                state.serialize_field("k", k)?;
                state.serialize_field("p", p)?;
                state.end()
            }
        }
    }
}

fn main() {
    let x = Variants::VariantB { k: 5, p: 5.0 };
    let toml_str = toml::to_string(&x).unwrap();
    println!("{}", toml_str);
}

The code compiles, but when I run it it fails:代码可以编译,但是当我运行它时失败了:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: UnsupportedType', src/libcore/result.rs:999:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

I figured the issue must be in my use of the API, so I consulted the API documentation for StructVariant and it looks practically the same as my code.我认为问题一定出在我对 API 的使用上,因此我查阅了StructVariant的 API 文档,它看起来与我的代码几乎相同。 I'm sure I'm missing something, but I don't see it based on the docs and output.我确定我遗漏了一些东西,但我没有根据文档和输出看到它。

The TOML format does not support enums with values: TOML 格式不支持带有值的枚举:

use serde::Serialize; // 1.0.99
use toml; // 0.5.3

#[derive(Serialize)]
enum A {
    B(i32),
}

fn main() {
    match toml::to_string(&A::B(42)) {
        Ok(s) => println!("{}", s),
        Err(e) => eprintln!("Error: {}", e),
    }
}
Error: unsupported Rust type

It's unclear what you'd like your data structure to map to as TOML.目前尚不清楚您希望将数据结构映射为 TOML。 Using JSON works just fine:使用 JSON 效果很好:

use serde::Serialize; // 1.0.99
use serde_json; // 1.0.40

#[derive(Serialize)]
enum Variants {
    VariantA,
    VariantB { k: u32, p: f64 },
}

fn main() {
    match serde_json::to_string(&Variants::VariantB { k: 42, p: 42.42 }) {
        Ok(s) => println!("{}", s),
        Err(e) => eprintln!("Error: {}", e),
    }
}
{"VariantB":{"k":42,"p":42.42}}

Enabling external tagging for the enum enables Serde to serialize/deserialize it to TOML:为枚举启用外部标记使 Serde 能够将其序列化/反序列化为 TOML:

#[derive(Deserialize)]
#[serde(tag = "type")]
enum Variants {
    VariantA,
    VariantB { k: u32, p: f64 },
}

toml::to_string(&Variants::VariantB { k: 42, p: 13.37 })

serializes to序列化为

type = VariantB
k = 42
p = 13.37

This works well in Vec s and HashMap s, too.这也适用于VecHashMap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在Swift中尝试序列化JSON时会出现错误? - Why do I get an error when trying to serializing JSON in Swift? Java:序列化对象时,我从不尝试序列化的类中获取NotSerializableException - Java: when serializing an object, I get NotSerializableException from classes I'm not trying to serialize 在 C# 中序列化枚举时如何解决程序集 ID 错误? - How to solve assembly ID error when serializing enum in C#? 如何在不包含枚举变量名称的情况下序列化枚举? - How do I serialize an enum without including the name of the enum variant? 为什么我可以通过Bundle传递带有位图的可序列化但在系统尝试对其进行序列化时出现错误? - Why can I pass a serializable with a bitmap through a Bundle but get an error when the system tries to serialize it? 如何为套接字编程序列化8位整数的结构? - How do I serialize a struct of 8bit integers for socket programming? 序列化带有参数情况的枚举结构 - Serialize enum struct that have cases with arguments 为什么在反序列化Ruby对象时会出错? - Why do I get an error when deserializing a Ruby object? 为什么这个结构不序列化? - Why doesn't this struct serialize? 从接口序列化通用类时,如何让DataContractJsonSerializer在类型提示中使用具体类型 - How do I get DataContractJsonSerializer to use concrete type in type hint when serializing generic class from interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM