我正在尝试通过Rust中的OpenWeather API获取数据,但是我想在解析方面会遇到一些麻烦

时间:2019-11-17 18:21:28

标签: api rust rust-cargo rust-crates rustup

extern crate openweather;
use openweather::LocationSpecifier;
static API_KEY: &str = "e85e0a3142231dab28a2611888e48f22";

fn main() {
    let loc = LocationSpecifier::Coordinates {
        lat: 24.87,
        lon: 67.03,
    };
    let weather = openweather::get_current_weather(loc, API_KEY).unwrap();

    print!(
        "Right now in Minneapolis, MN it is {}K",
        weather.main.humidity
    );
}
  

错误:线程“ main”在“ Result::unwrap()   Err值:ErrorReport {编码:0,消息:“收到意外响应:   \“ {\\” coord \\“:{\\” lon \\“:67.03,\\” lat \\“:24.87},\\” weather \\“:[{\\” id \\“ :803,\\“ main \\”:\\“ Clouds \\”,\\“ description \\”:\\“ broken   clouds \\“,\\” icon \\“:\\” 04n \\“}],\\” base \\“:\\” stations \\“,\\” main \\“:{\\ “ temp \\”:294.15,\\“ pressure \\”:1018,\\“湿度\”“:60,\\” temp_min \\“:294.15,\\” temp_max \\“:294.15},\ \“可见性\”:6000,\\“风\\”:{\\“速度\\”:5.1,\\“度\”:30},\\“乌云\”:{\\ “ all \\”:70},\\“ dt \\”:1574012543,\\“ sys \\”:{\\“ type \\”:1,\\“ id \\”:7576,\\ “ country \\”:\\“ PK \\”,\\“ sunrise \\”:1573955364,\\“ sunset \\”:1573994659},\\“时区\”:18000,\\“ id \ \“:1174872,\\”名称\\“:\\” Karachi \\“,\\”鳕鱼\“:200} \”“   }

1 个答案:

答案 0 :(得分:0)

问题是由于反序列化结构与OpenWeather的JSON不匹配而导致的JSON解析错误,也许是API最近添加了此错误?在您的示例中,OpenWeatherCurrent结构体缺少timezone

但是似乎有一个open PR可以解决此问题,您可以通过以下操作对其进行测试:

  • 将您的Cargo.toml依赖项更改为openweather = { git = "https://github.com/caemor/openweather" }
  • PR作者还更新了get_current_weather签名,因此您需要将第2、10行更改为以下内容:

    use openweather::{LocationSpecifier, Settings};
    
    let weather = openweather::get_current_weather(&loc, API_KEY, &Settings::default()).unwrap();