Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I've read
the docs
, but I haven't seen a way to solve my problem. I'm parsing an API response which on success would return only a 2xx status code, while on bad requests it sends JSON.
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
fn main() {
let _: X = serde_json::from_str(r#"{ "ok": true }"#).expect("with string");
let _: X = serde_json::from_str("").expect("empty string");
#[derive(Deserialize)]
struct X {
ok: Option<bool>,
Playground
This is the struct I would like to deserialize into. I've tried adding #[serde(skip_serializing_if = "some_func")]
to the field, but it doesn't change anything.
The error is
Error("EOF while parsing a value", line: 1, column: 0)
Is there a way to handle this properly, or do I always have to check the status code if it's 2xx before attempting to deserialize the response?
–
–
–
–
–
The main problem here is that the empty string is not valid JSON according to most parsers including the one built into ES6 and apparently Serde. There are three possible solutions that I see to this problem.
Return an empty dict from the endpoint
Do not blindly attempt deserialization of the empty string checking first for the content length of the response body.
Implement a custom Deserialize
method
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.