rust把json字符串转为结构体的一些经验

发布时间:2022-02-17 12:16:21 浏览数:56

在rust里面处理json字符串时,一个常用的库是serde_json,网上也有很多资料,这里就不再赘述了。如

  • https://www.qttc.net/509-rust-parse-json.html
  • https://docs.rs/serde_json/latest/serde_json/

这里分享一下我的一点经验:

这里是常规的把字符串转为结构体的代码

#[derive(Debug,Deserialize)]
struct ConfigStruct {
    username: String,
    password: String
}

pub async fn demo() {
    let config_str = r#"{"username":"hello","password":"world"}"#;
    let config: ConfigStruct = serde_json::from_str(config_str).unwrap();
    println!("config is {:?}", config);
}

这里config_str是固定的正确的,但是我的需求里面,是需要前端传来我想要结构的json字符串,但是如果前端传来的不是我想要的结构的呢,那直接调用unwrap的话,就会直接panic,导致程序挂掉。

所以我想要的是,在后端接收前端传来的json字符串,然后尝试转为想要的结构体来验证参数是否正确。

如果参数正确,那么逻辑继续,如果参数错误,就要返回提示,而不是直接在程序里面panic

修改后的代码是

#[derive(Debug,Deserialize)]
struct ConfigStruct {
    username: String,
    password: String
}

pub async fn demo() {
    //暂定下面两个字符串是前端传来的
    let config_str = r#"{"user":"hello","pwd":"world"}"#; //错误参数
    // let config_str = r#"{"username":"hello","password":"world"}"#;//正确参数

    let config_res= serde_json::from_str(config_str).map(|c:ConfigStruct| c);
    if config_res.is_err() {
        println!("传来的参数错误,错误信息是{:?}", config_res.unwrap_err().to_string());
    }else {
        println!("传来的参数正确");
        println!("config is {:?}", config_res.unwrap());
    }
}