简体   繁体   English

当 Rust 中的变体过多时,使用枚举建模 API JSON 响应

[英]Modeling API JSON response with enum when there are too many variants in Rust

My question is pretty simple - what are the ways I can model a JSON response of, eg, stock prices.我的问题很简单——我可以通过哪些方式 model 对 JSON 做出响应,例如股票价格。 Let's say I want to model a JSON response of a price query request that gives me stock names and prices, like:假设我想 model 一个价格查询请求的 JSON 响应,它给了我股票名称和价格,例如:

{"AAPL": {"usd": 10}, "GOOG": {"usd": 20} ...}

If I model this with an enum together with serde crate, it will require me to list a huge number of stock variants, and even if I'll somehow manage to do that, it will still be very inefficient because new stocks are added constantly and I won't be able to properly maintain the variants list.如果我 model 这个带有枚举和serde crate,它将需要我列出大量的库存变体,即使我能设法做到这一点,它仍然会非常低效,因为不断添加新库存并且我将无法正确维护变体列表。 So the following is not feasible:所以以下是不可行的:

#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PriceResponse {
    AAPL(HashMap<String, HashMap<String, f32>>),
    GOOG(HashMap<String, HashMap<String, f32>>),
    ...
    ...
}

I do want to make use of rust's type system to make the response more "typed", but I don't know how to do it.我确实想利用 rust 的类型系统来使响应更加“类型化”,但我不知道该怎么做。 Ideally, I want to get an enum or a struct back.理想情况下,我想取回一个枚举或结构。

If I understand you, your data is of the format HashMap<String, HashMap<String, f32>> but you want to parse it into something with types that are more representative of the data.如果我理解您,您的数据格式为HashMap<String, HashMap<String, f32>>但您希望将其解析为更能代表数据的类型。 Could you define structs that represent your data but are not enums?你能定义代表你的数据但不是枚举的结构吗? Enums are for when the data can take different forms or have different meanings, but in this case every stock seems semantically the same.枚举适用于数据可以采用不同的 forms 或具有不同含义的情况,但在这种情况下,每只股票在语义上似乎都是相同的。 According to the serde documentation , you won't need to do extra work to get serde to deserialize the inner field.根据 serde文档,您不需要做额外的工作来让serde反序列化内部字段。

struct Stock(pub String);
struct CurrencyName(pub String);
struct Price(pub i32); // currencies are typically stored as integer
struct StockResponse(pub Hashmap<Stock, HashMap<CurrencyName, Price>>);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM