How to convert a String type to a Json Object

How can i convert a String to a Json object using the serde_json crate

"{\"statusCode\":400,\"message\":\"Reference already exists\",\"error\":\"Bad Request\"}"

This is what i'm currently doing and it produces this error

let response_body = response.text().await.unwrap();
println!("{:?}", serde_json::from_str(&response_body));

`cannot infer type for type parameter T declared on the function from_str`

Then when i remove the borrow notation from the response_body in from_str i get this error

expected &str, found struct std::string::String

This means that Rust doesn't know, to what you're trying to convert from string. You can store the parsed value in explicitly typed variable:

struct ParsedType { /* fields */ }
let parsed: ParsedType = serde_json::from_str(&response_body).unwrap();
println!("{:?}", parsed);
2 Likes

Thanks for responding.

What if i don't know what kind of fields would be produced from the response_body how do i go about creating struct ParsedType { /* fields */ } ?

If you want a general JSON type, you can use serde_json::Value.

    println!("{:?}", serde_json::from_str::<serde_json::Value>(s));

Playground.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.