0

我正在使用tomlnum -bigintserde来反序列化以下数据:

[[trades]]
action = "Buy"
date_time = 2019-04-15T15:36:00+01:00
fee = [1, [44000000]]
id = "#1"
price = [-1, [20154500000]]
quantity = [1, [200000000]]

但我收到了这个错误:

Error: Error { inner: ErrorInner { kind: Custom, line: Some(7), col: 14, at: Some(156), message: "invalid value: integer `20154500000`, expected u32", key: ["trades", "price"] } }

当然,如果我使价格值小于u32::MAX,程序编译得很好。但我想使用这个高值,因为我将数字缩放 1e8 以避免处理浮点运算。

是否可以让 serde 反序列化BigInts 来u64代替?

use num_bigint::BigInt;
use serde_derive::Deserialize;
use toml::from_str;
use toml::value::Datetime;

#[derive(Debug, Deserialize)]
pub struct Trade {
    pub action: String,
    pub date_time: Datetime,
    pub fee: BigInt,
    pub id: Option<String>,
    pub price: BigInt,
    pub quantity: BigInt,
}

#[derive(Debug, Deserialize)]
pub struct TradeTable {
    pub trades: Vec<Trade>,
}

fn main() {
    let trades_string: String = String::from("[[trades]]\naction = \"Buy\"\ndate_time = 2019-04-15T15:36:00+01:00\nexchange = \"Degiro\"\nfee = [1, [44000000]]\nid = \"#1\"\nprice = [-1, [20154500000]]\nquantity = [1, [200000000]]");
    let trade_table: TradeTable = from_str(&trades_string).unwrap();
    let trades: Vec<Trade> = trade_table.trades;
}

另外,这里是 Rust Playground 的链接。请注意,您需要将代码复制到本地计算机,因为您需要以下serde功能num-bigint

货运.toml

[dependencies.num-bigint]
version = "0.2.6"
features = ["serde"]
4

1 回答 1

3

你是如何创建这个文件的——你是通过序列化 BigInt 来创建的,还是手动编写的?

我手写的数据。

您的数据无效,以下工作:

use num_bigint::BigInt;
use std::str::FromStr;

#[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq)]
pub struct Trade {
    pub price: BigInt,
}

fn main() {
    let price = BigInt::from_str("-201545000000000").unwrap();
    let trade = Trade { price };

    let j = serde_json::to_string(&trade).unwrap();
    println!("{}", j);
    let a: Trade = serde_json::from_str(&j).unwrap();
    assert_eq!(trade, a);

    let j = toml::to_string(&trade).unwrap();
    println!("{}", j);
    let b: Trade = toml::from_str(&j).unwrap();
    assert_eq!(trade, b);
}

您不应该手动创建它。

于 2020-03-13T18:04:31.570 回答