您可以以更多代码为代价提高效率。如果您创建自己的实现,Vec
则不需要反序列化:Visitor
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use std::collections::HashMap;
use std::fmt;
use serde::de::{Deserialize, Deserializer, Visitor};
#[derive(Debug, Default)]
struct Data {
luminosity: Vec<Option<String>>,
color: Vec<Option<String>>,
}
struct Wrapper(HashMap<String, Data>);
impl<'de> Deserialize<'de> for Wrapper {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_seq(WrapperVisitor)
}
}
struct WrapperVisitor;
impl<'de> Visitor<'de> for WrapperVisitor {
type Value = Wrapper;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a sequence of measurement objects")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
#[derive(Debug, Deserialize)]
struct DataPoint {
sensor: String,
luminosity: Option<String>,
color: Option<String>,
}
let mut all_data = HashMap::new();
while let Some(data_point) = seq.next_element::<DataPoint>()? {
let data = all_data
.entry(data_point.sensor)
.or_insert_with(Data::default);
data.luminosity.push(data_point.luminosity);
data.color.push(data_point.color);
}
Ok(Wrapper(all_data))
}
}
fn main() {
let input = r###"
[
{
"sensor": "left",
"luminosity": "50",
"color": "(255,0,0)"
},
{
"sensor": "left",
"color": "#0f0"
},
{
"sensor": "right",
"luminosity": "20"
},
{
"sensor": "right",
"luminosity": "40",
"color": "(255,0,0)"
},
{
"sensor": "left",
"luminosity": "30"
},
{
"sensor": "top",
"luminosity": "10"
},
{
"sensor": "right",
"color": "(0,0,0)"
}
]
"###;
let data = serde_json::from_str::<Wrapper>(input).expect("Nope");
let data = data.0;
println!("{:#?}", data);
}
这将产生输出:
{
"left": Data {
luminosity: [
Some("50"),
None,
Some("30")
],
color: [
Some("(255,0,0)"),
Some("#0f0"),
None
]
},
"right": Data {
luminosity: [
Some("20"),
Some("40"),
None
],
color: [
None,
Some("(255,0,0)"),
Some("(0,0,0)")
]
},
"top": Data {
luminosity: [
Some("10")
],
color: [
None
]
}
}