3

我有一个使用枚举的结构,但是在打印时它给出了枚举名称和值,而不仅仅是值。我想使用 serde_json 序列化它以作为 JSON 请求发送。

我想将结构重新用于 geth json-rpc 的不同命令,而不是为每种类型的命令制作不同的结构。这就是为什么我想到使用枚举。但我做错了什么。可能是打印,但 json-rpc 表示该参数也无效。

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
enum Params {
    String (String),
    Boolean (bool)
}

#[derive(Debug, Serialize, Deserialize)]
struct EthRequest {
    jsonrpc : String,
    method: String,
    params: [Params; 2],
    id: i32
}


fn main() {
   let new_eth_request = EthRequest {
        jsonrpc : "2.0".to_string(),
        method : "eth_getBlockByNumber".to_string(),
        params : [Params::String("latest".to_string()), Params::Boolean(true)],
        id : 1
    };
   println!("{:#?}", new_eth_request);

}

输出:

EthRequest {
    jsonrpc: "2.0",
    method: "eth_getBlockByNumber",
    params: [
        String(
            "latest",
        ),
        Boolean(
            true,
        ),
    ],
    id: 1,
}

我需要的是 params 字段params: ["latest",true]

4

1 回答 1

3

提供的输出来自Debug实现,而不是来自 serde。从 serde 你会得到:

{
  "jsonrpc": "2.0",
  "method": "eth_getBlockByNumber",
  "params": [
    {
      "String": "latest"
    },
    {
      "Boolean": true
    }
  ],
  "id": 1
}

我猜你想删除标签StringBoolean枚举值前面。这很容易做到,只需用以下方式注释您的枚举#[serde(untagged)]

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
enum Params {
    String (String),
    Boolean (bool)
}

你会得到预期的输出:

{
  "jsonrpc": "2.0",
  "method": "eth_getBlockByNumber",
  "params": [
    "latest",
    true
  ],
  "id": 1
}

您可以在serde 的文档中了解有关不同枚举表示的更多信息。

于 2021-06-16T17:43:16.837 回答