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

得到的结果数据:

相关推荐
木风小助理17 小时前
在 Spring Boot 中实现 JSON 字段的蛇形命
spring boot·后端·json
Source.Liu18 小时前
【Rust】函数
rust
huatian518 小时前
Rust 语法整理
开发语言·后端·rust
九月生1 天前
Rust CLI 项目构建指南
rust
Hqst_xiangxuajun1 天前
万兆SFP光纤笼子交换机和PCIE网卡主板上起到什么作用
网络·fpga开发·oracle·sqlite·json·信息与通信
徐安安ye1 天前
Flutter 与 Rust 混合开发:打造毫秒级响应的高性能计算引擎
开发语言·flutter·rust
浪客川1 天前
rust入门案例-猜数字游戏
开发语言·rust
3824278271 天前
python:输出JSON
前端·python·json
Source.Liu1 天前
【Rust】方法
rust