Error handling while parsing json


#1

Below is a simple application that tries to parse a json string.
Unforturnately I can’t get it to compile without an error.

Thanks in advance!

Compile error:

src/main.rs:15:6: 15:7 error: unable to infer enough type information about `_`; type annotations or generic parameter binding required [E0282]
src/main.rs:15          Ok(x) => {
                           ^
src/main.rs:15:6: 15:7 help: run `rustc --explain E0282` to see a detailed explanation

Code:

extern crate rustc_serialize;

use rustc_serialize::json;

#[derive(RustcDecodable, RustcEncodable)]
pub struct Status  {
	volume: i32
}


fn main() {
	let body = "{ \"volume\" : -0 }";
	println!("Body: {:?}", body);
	match json::decode(&body) {
		Ok(x) => {
			println!("Ok");
		},
		Err(_) => {
			println!("Ok");
		}
	};
}

/*
// Main that works but without error handling
fn main() {
	let body = "{ \"volume\" : -0 }";
	println!("Body: {:?}", body);
	let _: Status = json::decode(&body).unwrap();
}
*/

#2

You dropped the type annotation from the working example. Note that decode is generic:

http://doc.rust-lang.org/rustc-serialize/rustc_serialize/json/fn.decode.html

The compiler must know what T is. In your case, it is Status. You can either do that by clarifying that when binding to a variable, or at the site of the call.

Here, the latter is probably recommendable. Use:

match json::decode::<Status>(&body) {
  ...
}

#3

Thank you very much for your help! Works great!