REST: deserializing the request into struct

I have a bit of a problem with rest calls I am using Reston and once I call get() on a given url I get retrieve my request but there is a Deserialization problem:



use serde::{Deserialize};
use restson::{RestClient,RestPath,Error};

use serde_json::Value;

#[derive(Deserialize, Debug)]
struct Obj {
    items: Vec<Calls>,
}

#[derive(Deserialize, Debug)]
struct Calls {
    id: String,
}

impl RestPath<()> for Obj {
    fn get_path(
		_ : ()
		) -> Result<String, Error> {
			Ok(String::from("mx"))
    }   
}


fn main(){


//  Gets returned by rest call ---> "[{\"id\":\"/mx/1\"},{\"id\":\"/mx/2\"},{\"id\":\"/mx/3\"},{\"id\":\"/mx/4\"}]";
let client = RestClient::new(&url).unwrap();
let data: Obj = client.get(()).unwrap();
// Error: 
// thread 'Map' panicked at 'called `Result::unwrap()`
// on an `Err` value: DeserializeParseError(Error("invalid 
// type: map, expected a sequence", line: 1, column: 1), 
// "[{\"id\":\"/mx/1\"},{\"id\":\"/mx/2\"},{\"id\":\"/mx/3\"},{\"id\":\"/mx/4\"}]"


for i in data {
        println!("{:#?}", i);
    }
}

What should the structure look like for which the RestPath is implemented ? Can I somehow avoid this heavy structs and replace them with Value object from serde_json ?

thnx

#[derive(Deserialize, Debug)]
struct Item {
    id: String,
}

// ...

let data: Vec<Item> = client.get(()).unwrap();

You could use Value, but then you have to manually check that the JSON matches what you expect (that it's a list, that each of the items is an object, that they all have ids, etc.)

1 Like

the reston is a problem ...

let data: Vec<Item> = client.get(()).unwrap();
    |                        ^^^ the trait `restson::RestPath<()>` is not implemented for `std::vec::Vec<rest::Item>`

Then you'll just need the wrapper type to be something like

#[derive(Deserialize, Debug)]
struct Obj(Vec<Item>);

// ...

let data: Obj = client.get(()).unwrap();

Basically the same as your original, but Obj is a single element tuple struct.

2 Likes