Unable to deserialize json to struct in rust [duplicate] - rust

This question already has an answer here:
How do I fix "cannot find derive macro in this scope"?
(1 answer)
Closed 2 years ago.
I am trying to Deserialize a string to a struct in rust. The below code is from json_serde documentation only.
use serde::{Deserialize, Serialize};
use serde_json::Result;
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
phones: Vec<String>,
}
fn main() {
let data = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;
// Parse the string of data into a Person object. This is exactly the
// same function as the one that produced serde_json::Value above, but
// now we are asking it for a Person as output.
let p: Person = serde_json::from_str(data).expect("bal");
// Do things just like with any other Rust data structure.
println!("Please call {} at the number {}", p.name, p.phones[0]);
}
The above code snippet gives me an error:
Compiling test-json-rs v0.1.0 (/Users/asnimpansari/Desktop/Personal/test-json-rs)
error: cannot find derive macro `Serialize` in this scope
--> src/main.rs:4:10
|
4 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^
error: cannot find derive macro `Deserialize` in this scope
--> src/main.rs:4:21
|
4 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
warning: unused imports: `Deserialize`, `Serialize`
--> src/main.rs:1:13
|
1 | use serde::{Deserialize, Serialize};
| ^^^^^^^^^^^ ^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
warning: unused import: `serde_json::Result`
--> src/main.rs:2:5
|
2 | use serde_json::Result;
| ^^^^^^^^^^^^^^^^^^
error[E0277]: the trait bound `Person: serde::de::Deserialize<'_>` is not satisfied
--> src/main.rs:25:21
|
25 | let p: Person = serde_json::from_str(data).expect("bal");
| ^^^^^^^^^^^^^^^^^^^^ the trait `serde::de::Deserialize<'_>` is not implemented for `Person`
|
::: /Users/asnimpansari/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.55/src/de.rs:2584:8
|
2584 | T: de::Deserialize<'a>,
| ------------------- required by this bound in `serde_json::de::from_str`
error: aborting due to 3 previous errors
For more information about this error, try `rustc --explain E0277`.
error: could not compile `test-json-rs`.
To learn more, run the command again with --verbose.
My Cargo.toml file has below dependencies
[dependencies]
serde_json = "1.0.55"
serde = "1.0.100"
Despite importing Serialize and Deserialize from the serde and adding to struct. It gives me an error.
What part am I doing wrong here?

You need to activate the derive macros feature in your Cargo.toml:
serde = { version = "1.0", features = ["derive"] }

Related

oneshot::channel `tokio::sync::oneshot::Receiver<()>` is not an iterator add `use futures_util::FutureExt`

In the tokio tests I see they use oneshot::channel together with serve_with_shutdown but the the compiler tells me to add use futures_util::future::future::FutureExt but as you can see in the example below I already added that trait to the scope.
What am I missing?
Here a reprex
run cargo new tokio-test
Cargo.toml
[package]
name = "tokio-test"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tonic = "0.7"
prost = "0.10.1"
tokio = { version = "1.18", features = ["macros", "rt-multi-thread"] }
[build-dependencies]
tonic-build = "0.7.2"
src/main.rs
pub mod console {
tonic::include_proto!("console");
}
use console::console_server::{Console, ConsoleServer};
use console::{ConsoleResponse, InfoRequest};
use tokio::runtime::Runtime;
use tokio::sync::oneshot;
use tonic::{transport::Server, Request, Response};
use futures_util::FutureExt;
#[derive(Default)]
pub struct ConsoleImpl {}
#[tonic::async_trait]
impl Console for ConsoleImpl {
async fn info(
&self,
request: Request<InfoRequest>,
) -> Result<Response<ConsoleResponse>, tonic::Status> {
println!("{}", request.get_ref().text);
Ok(Response::new(ConsoleResponse {}))
}
}
fn main() {
let addr = "[::1]:50051".parse().unwrap();
let maxconsole = ConsoleImpl::default();
println!("Console server listening on {}", addr);
let mut rt = Runtime::new().expect("failed to obtain a new RunTime object");
let (shutdown_send, shutdown_recv) = oneshot::channel::<()>();
let server_future = Server::builder()
.add_service(ConsoleServer::new(maxconsole))
// .serve(addr)
.serve_with_incoming_shutdown(
addr,
shutdown_recv.map(drop),
);
rt.block_on(server_future).expect("failed to successfully run the future on RunTime");
}
src/console.proto
syntax = "proto3";
package console;
service Console {
rpc info (InfoRequest) returns (ConsoleResponse) {}
}
message InfoRequest {
string text = 1;
}
message ConsoleResponse {
}
If you build the project it will complain
❯ cargo build
Updating crates.io index
Compiling tokio-test v0.1.0 (C:\s\tokio-test)
error[E0432]: unresolved import `futures_util`
--> src\main.rs:10:5
|
10 | use futures_util::FutureExt;
| ^^^^^^^^^^^^ use of undeclared crate or module `futures_util`
error[E0599]: `tokio::sync::oneshot::Receiver<()>` is not an iterator
--> src\main.rs:40:27
|
40 | shutdown_recv.map(drop),
| ^^^ `tokio::sync::oneshot::Receiver<()>` is not an iterator
|
::: C:\Users\FrancescElies\.cargo\registry\src\github.com-1ecc6299db9ec823\tokio-1.20.1\src\sync\oneshot.rs:318:1
|
318 | pub struct Receiver<T> {
| ---------------------- doesn't satisfy `tokio::sync::oneshot::Receiver<()>: Iterator`
|
= note: the following trait bounds were not satisfied:
`tokio::sync::oneshot::Receiver<()>: Iterator`
which is required by `&mut tokio::sync::oneshot::Receiver<()>: Iterator`
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
1 | use futures_util::future::future::FutureExt;
|
Some errors have detailed explanations: E0432, E0599.
For more information about an error, try `rustc --explain E0432`.
error: could not compile `tokio-test` due to 2 previous errors
Yes, you added the FutureExt import, but did not tell Rust where to find that crate. The critical part of the error message is:
error[E0432]: unresolved import `futures_util`
--> src\main.rs:10:5
|
10 | use futures_util::FutureExt;
| ^^^^^^^^^^^^ use of undeclared crate or module `futures_util`
This can be fixed by adding the futures_util crate to your Cargo.toml dependency section.

Declaring a hashmap (storageMap) in substrate

I want to create a StorageMap in substrate and am following this example to do that. The purpose of the storage map is to have a HashMap where the key will be the account ID of the user and the value will be the count of how many times an invalid transaction has been done. For example:
Adkqwd4324dqlwdOqwdd: 2,
XCvqwd4324dqlwdOqwdd: 0,
Adkqwd4324dqlwdOqwPu: 0,
Xcvqwd4324dqlwdOqwdd: 1
My current decl_storage macro inside transaction_payment>src>lib.rs looks like this:
decl_storage! {
/// StorageMap to keep track of invalid transactions
trait Store for Module<T: Trait> as InvalidTransactionCount {
InvalidTransactionCount get(fn invalid_transaction_count): map hasher(identity) T::AccountId => u32;
}
/// already present in the substrate master code
trait Store for Module<T: Config> as TransactionPayment {
pub NextFeeMultiplier get(fn next_fee_multiplier): Multiplier = Multiplier::saturating_from_integer(1);
StorageVersion build(|_: &GenesisConfig| Releases::V2): Releases;
}
}
However, when I compile this code, I am getting errors related to NextFeeMultiplier because it is not being initialized properly due to the error in the decl_storage macro because of InvalidTransactionCount StorageMap. Full traceback of error is given below:
error: unexpected token
--> frame/transaction-payment/src/lib.rs:242:2
|
242 | trait Store for Module<T: Config> as TransactionPayment {
| ^^^^^
error[E0433]: failed to resolve: use of undeclared type `NextFeeMultiplier`
--> frame/transaction-payment/src/lib.rs:259:4
|
259 | NextFeeMultiplier::mutate(|fm| {
| ^^^^^^^^^^^^^^^^^ use of undeclared type `NextFeeMultiplier`
error[E0433]: failed to resolve: use of undeclared type `NextFeeMultiplier`
--> frame/transaction-payment/src/lib.rs:446:3
|
446 | NextFeeMultiplier::get().saturating_mul_int(Self::weight_to_fee(weight))
| ^^^^^^^^^^^^^^^^^ use of undeclared type `NextFeeMultiplier`
error[E0599]: no function or associated item named `next_fee_multiplier` found for struct `Module<T>` in the current scope
--> frame/transaction-payment/src/lib.rs:414:27
|
249 | / decl_module! {
250 | | pub struct Module<T: Config> for enum Call where origin: T::Origin {
251 | | /// The fee to be paid for making a transaction; the per-byte portion.
252 | | const TransactionByteFee: BalanceOf<T> = T::TransactionByteFee::get();
... |
304 | | }
305 | | }
| |_- function or associated item `next_fee_multiplier` not found for this
...
414 | let multiplier = Self::next_fee_multiplier();
| ^^^^^^^^^^^^^^^^^^^ function or associated item
not found in `Module<T>`
warning: unused import: `StorageMap`
--> frame/transaction-payment/src/lib.rs:46:2
|
46 | StorageMap,
| ^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
error: aborting due to 4 previous errors; 1 warning emitted
Some errors have detailed explanations: E0433, E0599.
For more information about an error, try `rustc --explain E0433`.
error: could not compile `pallet-transaction-payment`
If I remove the InvalidTransactionCount trait Store from the decl_storage, then the code is being compiled fine.
Any help in identifying the correct way to declare a storage map inside the decl_storage macro will be highly appreciated. Thanks!
This line only can be written once. In the decl_module macro.
trait Store for Module<T: Config> as TransactionPayment {
If you want multi storage item just:
decl_storage! {
trait Store for Module<T: Trait> as InvalidTransactionCount {
InvalidTransactionCount get(fn invalid_transaction_count): map hasher(identity) T::AccountId => u32;
pub NextFeeMultiplier get(fn next_fee_multiplier): Multiplier = Multiplier::saturating_from_integer(1);
StorageVersion build(|_: &GenesisConfig| Releases::V2): Releases;
}
}

Rust/Rocket: the trait `serde::ser::Serialize` is not implemented for struct [duplicate]

This question already has answers here:
How do I fix "cannot find derive macro in this scope"?
(1 answer)
Why is a trait not implemented for a type that clearly has it implemented?
(1 answer)
Closed 2 years ago.
I'm trying to make a simple endpoint using Rocket. My Cargo.toml has these dependencies:
[dependencies]
rocket = "0.4.2"
rocket_codegen = "0.4.2"
rocket_contrib = "0.4.2"
main.rs looks like:
#[macro_use]
extern crate rocket;
use rocket_contrib::json::Json;
use serde::Serialize;
#[get("/org")]
fn getorg() -> Json<Org> {
Json(Org {
id: Option::from(25),
name: "Incredible-Customer".to_string(),
})
}
#[derive(Serialize)]
pub struct Org {
pub id: Option<i32>,
pub name: String,
}
fn main() {
rocket::ignite().mount("/", routes![getorg]).launch();
}
Compiling results in the errors:
error[E0432]: unresolved import `serde`
--> src/main.rs:3:5
|
3 | use serde::Serialize;
| ^^^^^ use of undeclared crate or module `serde`
error: cannot determine resolution for the derive macro `Serialize`
--> src/main.rs:14:10
|
14 | #[derive(Serialize)]
| ^^^^^^^^^
|
= note: import resolution is stuck, try simplifying macro imports
error[E0658]: `macro` is experimental
--> src/main.rs:7:1
|
7 | #[get("/org")]
| ^^^^^^^^^^^^^^
|
= note: see issue #39412 <https://github.com/rust-lang/rust/issues/39412> for more information
= help: add `#![feature(decl_macro)]` to the crate attributes to enable
= note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0277]: the trait bound `Org: serde::ser::Serialize` is not satisfied
--> src/main.rs:8:16
|
8 | fn getorg() -> Json<Org> {
| ^^^^^^^^^ the trait `serde::ser::Serialize` is not implemented for `Org`
|
::: /Users/shep/.cargo/registry/src/github.com-1ecc6299db9ec823/rocket-0.4.5/src/handler.rs:202:20
|
202 | pub fn from<T: Responder<'r>>(req: &Request, responder: T) -> Outcome<'r> {
| ------------- required by this bound in `handler::<impl rocket::Outcome<rocket::Response<'r>, rocket::http::Status, rocket::Data>>::from`
|
= note: required because of the requirements on the impl of `Responder<'_>` for `rocket_contrib::json::Json<Org>
I'm very confused as to how to look into this error. Is it a dependency issue? Why? I have versioned the rocket dependencies to the same one, but apparently this serde dependency is unhappy. Googling around claims it's a version mismatch inside one of my dependencies - but how do I go about solving that myself?
Add serde = {version = "1.0", features = ["derive"]} and serde_json = {version = "1.0"} to your cargo.toml to be able to derive from Serialize and Deserialize

Rust reqwest example json code does not compile

The example for dynamic json with reqwest
extern crate reqwest;
extern crate tokio;
extern crate serde_json; // added to after upgrade to 1.39.0
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let echo_json: serde_json::Value = reqwest::Client::new()
.post("https://jsonplaceholder.typicode.com/posts")
.json(&serde_json::json!({
"title": "Reqwest.rs",
"body": "https://docs.rs/reqwest",
"userId": 1
}))
.send()
.await?
.json()
.await?;
println!("{:#?}", echo_json);
// Object(
// {
// "body": String(
// "https://docs.rs/reqwest"
// ),
// "id": Number(
// 101
// ),
// "title": String(
// "Reqwest.rs"
// ),
// "userId": Number(
// 1
// )
// }
// )
Ok(())
}
failed to compile for rustc 1.38.0 with reqwest = "0.9.22" and tokio = "0.2.2":
Compiling pin-project-lite v0.1.1
error: `core::slice::<impl [T]>::len` is not yet stable as a const fn
--> /Users/mick/.cargo/registry/src/github.com-1ecc6299db9ec823/bytes-0.5.2/src/bytes.rs:121:18
|
121 | len: bytes.len(),
| ^^^^^^^^^^^
error: aborting due to previous error
error: Could not compile `bytes`.
This was fixed by upgrading as of the comment by Ömer below, but now the next problems are
error[E0433]: failed to resolve: could not find `main` in `tokio`
--> main.rs:5:10
|
5 | #[tokio::main]
| ^^^^ could not find `main` in `tokio`
error[E0277]: the trait bound `std::result::Result<reqwest::Response, reqwest::Error>: std::future::Future` is not satisfied
--> main.rs:7:40
|
7 | let echo_json: serde_json::Value = reqwest::Client::new()
| ________________________________________^
8 | | .post("https://jsonplaceholder.typicode.com/posts")
9 | | .json(&serde_json::json!({
10 | | "title": "Reqwest.rs",
... |
14 | | .send()
15 | | .await?
| |______________^ the trait `std::future::Future` is not implemented for `std::result::Result<reqwest::Response, reqwest::Error>`
error[E0277]: `main` has invalid return type `impl std::future::Future`
--> main.rs:6:20
|
6 | async fn main() -> Result<(), reqwest::Error> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ `main` can only return types that implement `std::process::Termination`
|
= help: consider using `()`, or a `Result`
error: aborting due to 3 previous errors
Some errors have detailed explanations: E0277, E0433.
For more information about an error, try `rustc --explain E0277`.
error: could not compile `webtrekk`.
To learn more, run the command again with --verbose.
and the next reqwest = "0.10.0-alpha.2" tokio = { version = "0.2.2", features = ["macros"] } serde_json = "1.0.44"
➜ rust git:(master) ✗ cargo run
Updating crates.io index
error: failed to select a version for `tokio`.
... required by package `reqwest v0.10.0-alpha.2`
... which is depended on by `webtrekk v0.1.0 (/Users/mick/repo/webtrekk-client/rust)`
versions that meet the requirements `= 0.2.0-alpha.6` are: 0.2.0-alpha.6
all possible versions conflict with previously selected packages.
previously selected package `tokio v0.2.2`
... which is depended on by `webtrekk v0.1.0 (/Users/mick/repo/webtrekk-client/rust)`
failed to select a version for `tokio` which could resolve this conflict
How can these be fixed?
Your example comes from https://github.com/seanmonstar/reqwest/blob/master/examples/json_dynamic.rs and works with the following Cargo.toml, using Rust 1.39:
[package]
name = "reqwest-json_dynamic-example"
version = "0.1.0"
authors = ["fyaa"]
edition = "2018"
[dependencies]
tokio = { version = "=0.2.0-alpha.6", features = ["io", "tcp", "timer"] }
reqwest = { version = "0.10.0-alpha.2", features = ["json"] }
serde_json = "1.0.44"

Serializing sub properties on a struct doesn't seem to work

I'm trying to serialize the following Result object, however I'm getting an error because while it workings for some of the properties, it doesn't seem to work on path, even though all of the elements involved have implementations provided by Serde.
#[macro_use]
extern crate serde;
extern crate rocket;
use rocket_contrib::json::Json;
use std::rc::Rc;
#[derive(Serialize)]
struct Result {
success: bool,
path: Vec<Rc<GraphNode>>,
visited_count: u32,
}
struct GraphNode {
value: u32,
parent: Option<Rc<GraphNode>>,
}
fn main(){}
fn index() -> Json<Result> {
Json(Result {
success: true,
path: vec![],
visited_count: 1,
})
}
Playground, although I can't get it to pull in the Rocket crate, it must not be one of the 100 most popular.
error[E0277]: the trait bound `std::rc::Rc<GraphNode>: serde::Serialize` is not satisfied
--> src/main.rs:11:5
|
11 | path: Vec<Rc<GraphNode>>,
| ^^^^ the trait `serde::Serialize` is not implemented for `std::rc::Rc<GraphNode>`
|
= note: required because of the requirements on the impl of `serde::Serialize` for `std::vec::Vec<std::rc::Rc<GraphNode>>`
= note: required by `serde::ser::SerializeStruct::serialize_field`
From my understanding, #[derive(Serialize)] should automatically create a serialize method which serde can then use. However I would expect it to work for the properties too. Do I need to create structs for all the types and then derive Serialize for all of those structs?
Do I need to do something to enable it?
The following crates are in use:
rocket = "*"
serde = { version = "1.0", features = ["derive"] }
rocket_contrib = "*"
the trait bound `std::rc::Rc<GraphNode>: serde::Serialize` is not satisfied
This means that Rc does not implement Serialize. See How do I serialize or deserialize an Arc<T> in Serde?. TL;DR:
serde = { version = "1.0", features = ["derive", "rc"] }
Once adding that, the error message changes to:
error[E0277]: the trait bound `GraphNode: serde::Serialize` is not satisfied
--> src/main.rs:11:5
|
11 | path: Vec<Rc<GraphNode>>,
| ^^^^ the trait `serde::Serialize` is not implemented for `GraphNode`
|
= note: required because of the requirements on the impl of `serde::Serialize` for `std::rc::Rc<GraphNode>`
= note: required because of the requirements on the impl of `serde::Serialize` for `std::vec::Vec<std::rc::Rc<GraphNode>>`
= note: required by `serde::ser::SerializeStruct::serialize_field`
That's because every type that needs to be serialized must implement Serialize:
#[derive(Serialize)]
struct GraphNode {

Resources