Confusion about the using of `serde_json`

I'm trying to deserialize a simple String:

serde_json::from_str::<(usize, usize)>("(1, 2)")
Err(Error("expected value", line: 1, column: 1))

But it shows the error. And the following work:

serde_json::from_str::<(usize, usize)>("[1, 2]")
Ok((1, 2))

What should I do if I want to deserialize "(1, 2)" to a type of (usize, usize)?

What you're trying to deserialize isn't standard JSON. It does look a little like RON, though. If your example is that simple, though, you can always write a manual parser.

5 Likes

You can try the following generic function to see the (de)serialization Rust Playground

fn check<T>(v: T)
where
    T: Serialize + DeserializeOwned + PartialEq + Debug,
{
    let s = serde_json::to_string(&v).unwrap();
    println!("{v:?} => {s}");
    let parsed: T = serde_json::from_str(&s).unwrap();
    assert_eq!(v, parsed);
}
3 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.