假设我们有一个 JSON 文档,其中属性之一是任意大的对象数组:
\n{\n "type": "FeatureCollection",\n "features":[\n {"type": "feature", ...},\n {"type": "feature", ...},\n ... many, many more objects ...\n ]\n}\n
Run Code Online (Sandbox Code Playgroud)\n该文档甚至可能通过网络发送,因此数组内的对象数量可能事先未知。
\n该文档可能有几 GB 大。
\n如何在 Rust 中解析这样的文档(最好使用 Serde)而不先将其加载到内存中?我只对数组中的对象感兴趣。\xe2\x80\x98parent\xe2\x80\x99 对象(如果愿意)可以被忽略。
\n我正在尝试实现 serde 的serialize_with属性。
我有这个代码:
use serde::Serializer;
pub fn serialize_json_as_string<S>(json: &serde_json::value::Value, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let string = serde_json::to_string(json).unwrap();
s.serialize_str(&string)
}
Run Code Online (Sandbox Code Playgroud)
我不喜欢unwrap()
倒数第二行。但我不知道如何将to_string
返回的错误转换为S::Error
.
我尝试let
用以下内容替换该行:
let string = serde_json::to_string(json)?;
Run Code Online (Sandbox Code Playgroud)
我得到了:
error[E0277]: `?` couldn't convert the error to `<S as serde::Serializer>::Error`
--> src/model/field_type.rs:30:45
|
26 | pub fn serialize_json_as_string<S>(json: &serde_json::value::Value, s: S) -> Result<S::Ok, S::Error>
| ----------------------- expected `<S as serde::Serializer>::Error` because of this
...
30 | let string …
Run Code Online (Sandbox Code Playgroud) 我使用 serde 和 bincode 使用自定义加载/保存方法定义了以下结构:
use std::{
fs::File,
io::{Read, Seek, SeekFrom, Write},
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Histogram {
pub bars: Vec<f64>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Histograms {
pub num_bars: usize,
pub num_histograms: usize,
pub vec: Vec<Histogram>,
}
fn main() {
println!("Hello, world!");
}
impl Histogram {
pub fn new(num_bars: usize) -> Histogram {
Histogram {
bars: vec![0.0; num_bars],
}
}
}
impl Histograms {
pub fn new(num_histograms: usize, num_bars: usize) -> …
Run Code Online (Sandbox Code Playgroud) #[derive(Deserialize)]
struct S<'d, T>
where T: Deserialize<'d>
{
foo: T,
other_field: String
}
Run Code Online (Sandbox Code Playgroud)
上面的代码无法编译,抱怨未使用的生命周期参数,但如果我删除它,Deserialize
就会丢失生命周期。
不使用幻像标记或 可以使上述代码正确吗DeserializeOwned
?