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

得到的结果数据:

相关推荐
weelinking7 小时前
【产品】11_实现后端接口——数据在背后如何流动
java·人工智能·python·sql·oracle·json·ai编程
alwaysrun12 小时前
Rust之代数数据类型Enum
后端·rust·编程语言
疏狂难除13 小时前
随便玩玩lldb(三)
rust·lldb
右耳朵猫AI14 小时前
Rust技术周刊 2026年第19周
开发语言·后端·rust
古城小栈16 小时前
cargo-pprof:Rust性能调优
人工智能·算法·rust
Vallelonga17 小时前
Rust 中的 Atomic 类型
rust
油炸自行车1 天前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
G_dou_1 天前
Linux 搭建 Rust 开发环境:从 rustup 安装到 Cargo 镜像
linux·rust
小灰灰搞电子2 天前
Rust 实现异步ModbusTCP主机源码分享
服务器·网络·modbustcp·rust
小杍随笔2 天前
【Rust 工具链管理完全指南:rustup toolchain 命令实战详解】
开发语言·后端·rust