无法使用带有serde

无法使用带有serde

本文介绍了无法使用带有serde-xml-rs的可选元素来解析XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一棵带有Serde注释的结构树,它成功解析了示例XML,包括以下片段:

I have a tree of serde-annotated structs and it succeeds in parsing the sample XML, including this fragment:

<bmsg>
    <cmsg>
         <!-- ... -->
    <cmsg>
<bmsg>

现在,我正在使用大型示例XML文件进行测试,由于有时缺少<cmsg>..</cmsg>,因此以下结构失败.我正在使用以下方法反序列化:

Now I am testing with a large sample XML file and the following structs fail because sometimes <cmsg>..</cmsg> is missing. I was deserializing this using:

#[derive(Serialize,Deserialize, Debug)]
struct A {
    #[serde(rename="bmsg")]
    messages: B,                 // <====
}

#[derive(Serialize,Deserialize, Debug)]
struct B {  // bmsg
    #[serde(rename="cmsg")]
    list: Vec<C>,
}

这在第二个结构中导致错误:

Which resulted in an error in the second struct:

panicked at 'called `Result::unwrap()` on an `Err` value: missing field `cmsg`

我将第一个结构更改为具有Vec<>,以便它可以处理可选元素:

I changed the first struct to have a Vec<> so it can deal with an optional element:

#[derive(Serialize,Deserialize, Debug)]
struct A {
    #[serde(rename="bmsg")]
    messages: Vec<B>,            // <====
}

#[derive(Serialize,Deserialize, Debug)]
struct B {  // bmsg
    #[serde(rename="cmsg")]
    list: Vec<C>,
}

但是serde继续出现相同的错误.我也尝试过Option<>,但没有成功.

But serde continues to give the same error. I tried Option<> too, but didn't get anywhere.

最让我感到困惑的是,我在各处使用Vec<>却从未遇到过这个问题.

What baffles me the most is that I use Vec<> all over the place and never ran into this problem.

推荐答案

它会出现Option<T>表示项确实存在

It would appear Option<T> means that the item does exist, it just is void of content.

文档似乎建议使用 default属性来告诉反序列化器对类型使用 Default特征的实现如果找不到它.

The documentation seems to suggest using the default attribute, to tell the deserializer to use the implementation of the Default trait for the type if it cannot be found.

考虑到这一点,也许这对您有用:

With that in mind, perhaps this would work for you:

#[derive(Serialize,Deserialize, Debug)]
struct A {
    #[serde(rename = "bmsg")]
    messages: B,
}

#[derive(Serialize,Deserialize, Debug)]
struct B {  // bmsg
    #[serde(rename = "cmsg", default)] // <----- use default to call `Default::default()` against this vector
    list: Vec<C>,
}

您可以找到我在操场上用来检查此代码的代码 .它不会在Playground中运行,但会在本地运行时产生预期的结果.

You can find the code I used to check this in the Playground. It won't run in the Playground, but it produces your expected results running locally.

这篇关于无法使用带有serde-xml-rs的可选元素来解析XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:19