如何迭代层次结构中的JSON对象?

我想在层次结构深处的对象中打印每个联系人的名称.每次制作合适的结构时,接触对象可能不具有完全相同数量的字段.我怎样才能做到这一点?

extern crate serde_json;

use serde_json::{Error, Value};
use std::collections::HashMap;

fn untyped_example() -> Result<(), Error> {
    // Some JSON input data as a &str. Maybe this comes from the user.
    let data = r#"{
      "name":"John Doe",
      "age":43,
      "phones":[
        "+44 1234567",
        "+44 2345678"
      ],
      "contact":{
        "name":"Stefan",
        "age":23,
        "optionalfield":"dummy field",
        "phones":[
          "12123",
          "345346"
        ],
        "contact":{
          "name":"James",
          "age":34,
          "phones":[
            "23425",
            "98734"
          ]
        }
      }
    }"#;

    let mut d: HashMap<String, Value> = serde_json::from_str(&data)?;
    for (str, val) in d {
        println!("{}", str);
        if str == "contact" {
            d = serde_json::from_value(val)?;
        }
    }

    Ok(())
}

fn main() {
    untyped_example().unwrap();
}

我是Rust的新手,基本上来自JavaScript背景.

最佳答案

may not have the exact same number of fields every time to make a
suitable structure

目前还不清楚你为什么这么想:

extern crate serde_json; // 1.0.24
#[macro_use]
extern crate serde_derive; // 1.0.70;

use serde_json::Error;

#[derive(Debug, Deserialize)]
struct Contact {
    name: String,
    contact: Option<Box<Contact>>,
}

impl Contact {
    fn print_names(&self) {
        println!("{}", self.name);

        let mut current = self;

        while let Some(ref c) = current.contact {
            println!("{}", c.name);

            current = &c;
        }
    }
}

fn main() -> Result<(), Error> {
    let data = r#"{
      "name":"John Doe",
      "contact":{
        "name":"Stefan",
        "contact":{
          "name":"James"
        }
      }
    }"#;

    let person: Contact = serde_json::from_str(data)?;
    person.print_names();

    Ok(())
}

我已经从JSON中删除了额外的字段以获得一个较小的示例,但如果它们存在则没有任何变化.

也可以看看:

> Learning Rust With Entirely Too Many Linked Lists
> Why are recursive struct types illegal in Rust?
> Rust & Serde JSON deserialization examples?

点赞