5

我想name在层次结构的深处打印对象中每个联系人的 。联系人对象可能不会每次都具有完全相同数量的字段来构建合适的结构。我怎样才能做到这一点?

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 背景。

4

2 回答 2

1

每次都可能没有完全相同数量的字段来制作合适的结构

不清楚你为什么这么认为:

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 中删除了额外的字段以提供一个较小的示例,但如果它们存在,则不会发生任何变化。

也可以看看:

于 2018-08-17T17:29:10.723 回答
1

通过 serde_json::value::Value 枚举进行阅读,我找到了您正在寻找的内容:

extern crate serde_json;
use serde_json::{Value};

fn main() {
    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 data: Value = serde_json::from_str(data).unwrap();
    read_value(&data, "name");
}

fn read_value(value: &Value,  search_word: &str) {
    for val in value.as_object().unwrap(){
        let (key, v) = val;
        if key == "name" {
            println!("> name: {}",v);
        }
        if v.is_object() { // if it is an object, check recursively
            read_value(&v, search_word);
        }
    }
}

它可以以非递归方式完成,但这是我能想到的更简单的形式。此外,我认为对于此类任务,递归实现看起来更优雅,代码更短。

于 2021-12-26T02:25:25.807 回答