Skip to content

Bug: an empty struct marked with #nserde(default) does not accept non-empty JSON objects #157

Description

@netheril96

I'm using an empty struct as a placeholder to assert that some object with a given key exists, but nanoserde fails if the object actually has any keys.

Here is a demo code

use nanoserde::DeJson;

/*
 * BUG DEMONSTRATION: nanoserde
 *
 * An empty struct marked with #[nserde(default)] does not accept any non-empty JSON object.
 * However, if the struct has at least one field, it correctly accepts (and ignores) extra fields.
 */

#[derive(DeJson, Debug)]
#[nserde(default)]
struct EmptyStruct {}

#[derive(DeJson, Debug)]
#[nserde(default)]
struct NonEmptyStruct {
    #[allow(dead_code)]
    _dummy: Option<i32>,
}

fn main() {
    let json = r#"{"extra": 123}"#;

    println!("Attempting to deserialize '{}' into EmptyStruct...", json);
    match EmptyStruct::deserialize_json(json) {
        Ok(s) => println!("Success: {:?}", s),
        Err(e) => println!("FAILED: {}", e),
    }

    println!("\nAttempting to deserialize '{}' into NonEmptyStruct...", json);
    match NonEmptyStruct::deserialize_json(json) {
        Ok(s) => println!("Success: {:?}", s),
        Err(e) => println!("FAILED: {}", e),
    }
}

Run result

Attempting to deserialize '{"extra": 123}' into EmptyStruct...
FAILED: Json Deserialize error: Unexpected token Str expected , or } , line:1 col:10

Attempting to deserialize '{"extra": 123}' into NonEmptyStruct...
Success: NonEmptyStruct { _dummy: None }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions