rustironrustc-serialize

Why can't I encode a struct into JSON with rustc-serialize?


I'm following an Iron web framework tutorial, which seemed pretty simple, but I can't seem to encode a struct as JSON.

extern crate iron;
extern crate rustc_serialize;

use iron::prelude::*;
use iron::status;
use rustc_serialize::json;

struct Greeting {
    msg: String,
}

fn main() {
    fn hello_world(_: &mut Request) -> IronResult<Response> {
        let greeting = Greeting { msg: "hello_world".to_string() };
        let payload = json::encode(&greeting).unwrap();
        // Ok(Response::with((status::Ok,payload)))
    }

    // Iron::new(hello_world).http("localhost:3000").unwrap();
}

My Cargo.toml:

[package]
name = "iron_init"
version = "0.1.0"
authors = ["mazbaig"]

[dependencies]
iron = "*"
rustc-serialize = "*"

And my error:

error: the trait bound `Greeting: rustc_serialize::Encodable` is not satisfied [E0277]
        let payload = json::encode(&greeting).unwrap();
                      ^~~~~~~~~~~~
help: run `rustc --explain E0277` to see a detailed explanation
note: required by `rustc_serialize::json::encode`

I kinda get that the right types aren't getting passed into the json.encode() function, but I'm having trouble figuring out what it wants from me. I'm probably missing something really basic.


Solution

  • You didn't provide the actual tutorial that you are using, but it appears to match this one from brson.

    extern crate iron;
    extern crate rustc_serialize;
    
    use iron::prelude::*;
    use iron::status;
    use rustc_serialize::json;
    
    #[derive(RustcEncodable)]
    struct Greeting {
        msg: String
    }
    
    fn main() {
        fn hello_world(_: &mut Request) -> IronResult<Response> {
            let greeting = Greeting { msg: "Hello, World".to_string() };
            let payload = json::encode(&greeting).unwrap();
            Ok(Response::with((status::Ok, payload)))
        }
    
        Iron::new(hello_world).http("localhost:3000").unwrap();
        println!("On 3000");
    }
    

    Notice anything different between the two?

    #[derive(RustcEncodable)]
    struct Greeting {
        msg: String
    }
    

    You have to specify that the Encodable trait is implemented. In this case, you can do so by deriving RustcEncodable.