Rust反序列JSON的小技巧

written on Fri 06 September 2019 by

serde是Rust中最流行的序列化和反序列化crate,这一篇就来记录下如何使用serde_json来反序列化连续的json对象。

比如有这样一段json数据:

{"start_pos": 0, "end_pos": 10}{"start_pos": 10, "end_pos": 30}
{"start_pos": 30, "end_pos": 40}

这段数据中,是三个连续的字段相同json对象,那么如何对这多个数据进行反序列化呢?

use serde::{Deserialize, Serialize};
use serde_json::Deserializer;

#[derive(Deserialize, Debug)]
struct Index {
    start_pos: u32,
    end_pos: u32,
}

fn main() {
    let data = r#"
    {"start_pos": 0, "end_pos": 10}{"start_pos": 10, "end_pos": 30}
    {"start_pos": 30, "end_pos": 40}
    "#;

    let mut indices = Deserializer::from_str(data).into_iter::<Index>();
    while let Some(idx) = indices.next() {
        println!("offset {}", indices.byte_offset() as u64);
        println!("idx => {:?}", idx.unwrap());
    }

}

Deserializer对象还有一个方法from_reader支持从文件对象中读取数据。

完结撒花!

This entry was tagged on #json, #rust and #serde

comments powered by Disqus
 

Tags