Rust serde 解析子结构的 Vec

Rust serde parse Vec of substruct

是否可以只提取此 json 项数组的消息结构?
如果项目中有多个条目,我的目标是获取 Message(s) 的 Vec。

{
  "items": [
    {
      "Message": {
        "data": "data",
        "header": "header"
      },
      "structx": {
        "val": 1
      },
      "val1": "test"
    }
  ]
}

截至目前,我有那些结构可以反序列化上述内容。

#[derive(Debug, Deserialize, Serialize)]
struct Items {
    items: Vec<Message>,
}

#[derive(Debug, Deserialize, Serialize)]
struct Message {
    #[serde(rename = "Message")]
    msg: Payload,
}

#[derive(Debug, Deserialize, Serialize)]
struct Payload {
    header: String,
    data: String,
}

我这样反序列化:

let x = json_string; // the above json
let msg: Items = serde_json::from_str(&x)?;

这行得通,但也许可以做得更干净。 我想到了这样的事情(这是行不通的),这样我就可以删除不必要的结构(项目,消息):

let msg: Vec<Payload> = serde_json::from_str(&x)?;

有3种解法:

  1. 处理它
  2. 实施自定义 Deserialize
  3. 使用不安全和#[repr(transparent)]:
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
#[repr(transparent)]
struct Items {
    items: Vec<Message>,
}

#[derive(Debug, Deserialize, Serialize)]
#[repr(transparent)]
struct Message {
    #[serde(rename = "Message")]
    msg: Payload,
}

#[derive(Debug, PartialEq, Deserialize, Serialize)]
struct Payload {
    header: String,
    data: String,
}

fn main() {
    let raw = r#"{
    "items": [{
        "Message": {
            "data": "data",
            "header": "header"
        },
        "structx": {
            "val": 1
        },
        "val1": "test"
    }]
}"#;

    let msg: Items = serde_json::from_str(&raw).unwrap();
    let payloads: Vec<Payload> = unsafe { std::mem::transmute(msg) };

    assert_eq!(
        payloads,
        vec![Payload {
            data: String::from("data"),
            header: String::from("header")
        }]
    );
}