8

serde_json::from_str我想制作一个能够从借来的数据( )或拥有的数据( )反序列化的 Serde 结构serde_json::from_reader。我已经阅读了理解反序列化器生命周期,并且理解了两个特征界限(<'de, T> where T: Deserialize<'de><T> where T: DeserializeOwned)之间的区别;我想要的是一个实现两个特征边界的结构,以便可以从任一反序列化函数中使用它。

以下代码(playground)拒绝编译:

use serde_json; // 1.0.56
use serde; // 1.0.114
use std::fs;
use std::io;
use std::borrow::Cow;

#[derive(serde::Deserialize)]
struct Resource<'s> {
    // The Cow should allow for either borrowed or owned data
    #[serde(borrow)]
    pub foo: Cow<'s, str>,
}

fn main() {
    {
        // Works as expected when referencing a string...
        let s = "{\"foo\":\"bar\"}";
        let resource: Resource = serde_json::from_str(s).unwrap();
    }
    {
        // ...but refuses to compile when reading from a file
        let file = fs::File::open("dummy.json").unwrap();
        let reader = io::BufReader::new(file);
        let resource: Resource = serde_json::from_reader(reader).unwrap();
    }
}

如何使该结构同时使用自有数据和借用数据?有没有办法做类似的事情#[serde(borrow_optional)]

4

1 回答 1

1

游乐场链接

对 的约束是不可能的serde_json::from_reader。但是,如果您自己构建它可能的Deserializer

        // ...but refuses to compile when reading from a file
        let file = fs::File::open("dummy.json").unwrap();
        let reader = io::BufReader::new(file);
        let mut deser = serde_json::Deserializer::from_reader(reader);
        let resource = Resource::deserialize(&mut deser).unwrap();
于 2022-02-09T07:02:20.497 回答