如何用Rust访问未知结构的JSON串,并包含对数组的访问?以下是一个简单的示例:
use serde_json::{Value};
fn main() {
let json_str = r#"{"name":"John","age":30,"city":"New York","hobbies":["reading","coding","gaming"]}"#;
// 解析JSON字符串
let json: Value = serde_json::from_str(json_str).unwrap();
// 访问特定的属性
if let Some(name) = json.get("name") {
println!("Name: {}", name);
}
if let Some(age) = json.get("age") {
println!("Age: {}", age);
}
if let Some(city) = json.get("city") {
println!("City: {}", city);
}
// 访问数组
if let Some(hobbies) = json.get("hobbies") {
if let Some(hobbies_array) = hobbies.as_array() {
for hobby in hobbies_array {
if let Some(hobby_str) = hobby.as_str() {
println!("Hobby: {}", hobby_str);
}
}
}
}
}