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对象了:

得到的结果数据:

相关推荐
Source.Liu13 小时前
【Rust】Cargo 命令详解
rust
大卫小东(Sheldon)20 小时前
集成AI 的 Redis 客户端 Rudist发布新版了
ai·rust·rudist
莫爷20 小时前
JSON 进阶技巧:Schema 验证、JSONPath 查询、性能优化
性能优化·json
无心水20 小时前
【时间利器】5、多语言时间处理实战:Go/C#/Rust/Ruby统一规范
golang·rust·c#·时间·分布式架构·openclaw·openclaw变现
Source.Liu21 小时前
【Rust】Rust 项目结构详解
rust
thulium_21 小时前
Rust 编译错误:link.exe 未找到
开发语言·后端·rust
Source.Liu1 天前
【rust】Rust 默认引用 std::prelude
rust
Source.Liu1 天前
【rust】VSCode Rust 开发扩展推荐
rust
莫爷1 天前
JSON vs XML vs YAML 深度对比:如何选择合适的数据格式?
xml·前端·json
ZTLJQ1 天前
序列化的艺术:Python JSON处理完全解析
开发语言·python·json