结构中的枚举数组打印变体名称和值
Array of enum in a struct prints variant names and value
我有一个使用枚举的结构,但在打印时它给出了枚举名称和值,而不仅仅是值。我想使用 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: ["latest",true]
提供的输出来自 Debug
实现,而不是来自 serde。从 serde 你会得到:
{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": [
{
"String": "latest"
},
{
"Boolean": true
}
],
"id": 1
}
我猜您想删除枚举值前面的标签 String
和 Boolean
。这很容易做到,只需用 #[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_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: ["latest",true]
提供的输出来自 Debug
实现,而不是来自 serde。从 serde 你会得到:
{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": [
{
"String": "latest"
},
{
"Boolean": true
}
],
"id": 1
}
我猜您想删除枚举值前面的标签 String
和 Boolean
。这很容易做到,只需用 #[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
}
中了解有关不同枚举表示的更多信息