在 Rust 中解析和提取复杂的 JSON 结构,你可以使用 serde_json
库来处理。 serde_json
提供了一组功能强大的方法来解析和操作 JSON 数据。
下面是一个示例,展示了如何解析和提取复杂的 JSON 结构:
use serde_json::{Value, Result};
fn main() -> Result<()> {// 假设有一个复杂的 JSON 字符串let json_str = r#"{"name": "John","age": 30,"address": {"street": "123 Main St","city": "New York","country": "USA"},"hobbies": ["reading", "gaming", "coding"],"friends": [{"name": "Alice", "age": 28},{"name": "Bob", "age": 32},{"name": "Charlie", "age": 27}]}"#;// 解析 JSON 字符串为 Value 类型let json_value: Value = serde_json::from_str(json_str)?;// 提取特定字段的值let name = json_value["name"].as_str().unwrap();let age = json_value["age"].as_u64().unwrap();let street = json_value["address"]["street"].as_str().unwrap();let hobbies = json_value["hobbies"].as_array().unwrap();let friends = json_value["friends"].as_array().unwrap();// 打印提取的值println!("Name: {}", name);println!("Age: {}", age);println!("Street: {}", street);println!("Hobbies: {:?}", hobbies);println!("Friends:");for friend in friends {let friend_name = friend["name"].as_str().unwrap();let friend_age = friend["age"].as_u64().unwrap();println!(" - Name: {}", friend_name);println!(" Age: {}", friend_age);}Ok(())
}
在这个示例中,我们首先将 JSON 字符串解析为 Value
类型的对象。然后,我们使用 Value
对象的索引操作符 []
来提取特定字段的值。你可以使用 as_*
方法将提取的值转换为你期望的类型,如字符串、整数等。注意,这里使用了 unwrap()
方法来简化代码,但在实际应用中,你可能需要处理错误情况。