结构体中的枚举数组打印变量名称和值

问题描述

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

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

use serde::{Deserialize,Serialize};

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

#[derive(Debug,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]

解决方法

提供的输出来自 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","params": [
    "latest",true
  ],"id": 1
}

您可以在 serde's documentation.

中了解有关不同枚举表示的更多信息