Skip to content

Deserializing Structs containing flattened RawValues always fails #599

@fegies

Description

@fegies
use serde_json::value::{Value,RawValue};
use serde::Deserialize;
use std::collections::HashMap;

#[derive(Deserialize, Debug)]
struct TestA<'a> {
    a: i32,
    #[serde(borrow)]
    #[serde(flatten)]
    rest: HashMap::<&'a str, &'a RawValue>,
}

#[derive(Deserialize, Debug)]
struct TestB<'a> {
    #[serde(borrow)]
    #[serde(flatten)]
    rest: HashMap::<&'a str, &'a RawValue>,
}

#[derive(Deserialize, Debug)]
struct TestC<'a> {
    #[serde(borrow)]
    #[serde(flatten)]
    rest: HashMap::<&'a str, Value>,
}

fn main() {
    let s = r#"{
        "a": 42,
        "b": "foo"
    }"#;
    let r = serde_json::from_str::<TestA>(s);
    println!("{:?}", r);
    let r = serde_json::from_str::<TestB>(s);
    println!("{:?}", r);
    let r = serde_json::from_str::<TestC>(s);
    println!("{:?}", r);
}

Output

Err(Error("invalid type: newtype struct, expected any valid JSON value", line: 4, column: 5))
Err(Error("invalid type: newtype struct, expected any valid JSON value", line: 4, column: 5))
Ok(TestC { rest: {"a": Number(42), "b": String("foo")} })

Expected behaviour

s is deserialized to all three structs successfully

Relevant Rust Playground

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1e2131c60a6b23e4a01c316786cbd7a6

Versions in use:

  • latest stable rustc 1.40.0
  • serde_json: 1.0.44
  • serde: 1.0.104

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions