rust将json字符串直接转为map对象或者hashmap对象

有些时候我们还真的不清楚返回的json数据里面到底有哪些数据,数据类型是什么等,这个时候就可以使用批处理的方式将json字符串转为一个对象,然后通过这个对象的get方法来获取json里面的数据。

rust 复制代码
    pub async fn test_json(&self) {
        let json_str = r#"
            {
                "name": "John",
                "age": 30,
                "city": "New York",
                "info": {
                    "work": "code",
                    "phone": 15670339888,
                    "password": "123456"
                }
            }
        "#;
        let map_obj: Value = serde_json::from_str(json_str).expect("Invalid JSON");
        let name = map_obj.get("name");
        println!("name value is:{name:?}");
        let info = map_obj.get("info");
        let mut phone;
        if info.is_some() {
            phone = info.expect("").get("phone");
            println!("phone number is: {phone:?}");
        }
    }

输出结果:

如果你使用的是reqwest请求库获取到的响应数据,那么你可以直接使用 response.json()方法来解析json数据,并将返回值声明为Value类型,得到的结果就是hashmap对象了:

得到的结果数据:

相关推荐
未来魔导16 小时前
go语言中json操作总结
数据分析·go·json
Source.Liu1 天前
【time-rs】DifferentVariant 错误类型详解(error/different_variant.rs)
rust·time
青鱼入云1 天前
@JsonValue和@JsonCreator介绍
json·jackson
Source.Liu1 天前
【time-rs】Format 错误枚举详解(error/format.rs)
rust·time
五仁火烧1 天前
安装rust开发环境
开发语言·后端·rust
RustCoder1 天前
Rust 1.92.0 发布:为 Never 类型铺路,强化调试与安全性
程序员·rust·编程语言
这儿有一堆花1 天前
JSON 与 MongoDB:直存对象的便利与隐性代价
数据库·mongodb·json
古城小栈1 天前
Go 与 Rust:系统编程语言的竞争与融合
开发语言·golang·rust
柒儿吖1 天前
深度实战:Rust交叉编译适配OpenHarmony PC——terminal_size完整适配案例
后端·rust·harmonyos
江公望1 天前
为什么Rust的编译工具依赖C语言的编译工具?
开发语言·rust