How to handle empty dictionary value in serde_json?

For example, If I have {"name": "jhon", "new_user": {}} How can I see If new_user key is present?
I tried using unit struct but got error
Error: Error("invalid type: map, expected unit struct NewUser", line: 1, column: 29)

use serde_json::Result;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct NewUser;

#[derive(Debug, Deserialize)]
struct Response {
    name: String,
    new_user: NewUser
}

fn main() -> Result<()>{
    let text = r#"{"name": "jhon", "new_user": {}}"#;
    let resp: Response = serde_json::from_str(text)?;
    println!("{:?}", resp);
    Ok(())
}

Playground

Structs with (zero or more) named fields expects JSON object. If it can be missing wrap it with the Option.

#[derive(Debug, Deserialize)]
struct NewUser {}

#[derive(Debug, Deserialize)]
struct Response {
    name: String,
    new_user: Option<NewUser>,
}
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.