0

Consider a fairly complex json, that describes a number of items, producers of those items, and a map of recipes for each item. My question is, if it is possible to deserialize a map of producers for respective items but (optionally) discarding the (deserialization) of recipes.

the minimal JSON looks like this:

{
    "items" : [
        "iron",
        "iron_ingot"
    ],
    "producers" : {
        "smelter": {
            "products" : {
                "iron_ingot" : {}
            },
            "energy" : 45.0
        }
    },
    "recipes": {
        "iron_ingot": {
            "items": {
                "iron": 12.0
            },
            "side_products": {},
            "amount": 12.0
        }
    }
}

There are a few structs involved:

#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum ProducerName {
    Smelter,
}

#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum Item {
    IronIngot,
    Iron,
}

#[derive(PartialEq, Default, Clone, Serialize, Deserialize, Debug)]
pub struct ItemProducer {
    // this maps an item with a production rule (eg. recipe)
    products: BTreeMap<Item, BTreeMap<Item, f64>>,

    energy: f64,
    kind: Option<ProducerName>,
}

(Some types are skipped, but can be found in the mrp). The specific question I have in mind, if it is possible to deserialize the field ItemProducer.products with the recipes in one go? Or do I have to manually copy the deserialized recipes?

Here is an mrp of the problem.

UPDATE: Converting the field products for each producer into a sequence / list of strings would reduce the effort.

tungsten
  • 63
  • 1
  • 6
  • *but (optionally) discarding the (deserialization) of recipes* — just... [leave the field out of the struct](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=61ff441fb5d3244c2ac0dfb242f0e5a8)? What you want isn't clear. Can you add an assertion that shows what you'd want? – Shepmaster May 05 '21 at 13:31
  • Your question may be answered by the answers of [How to transform fields during deserialization using Serde?](https://stackoverflow.com/q/46753955/155423). If not, please **[edit]** your question to explain the differences. – Shepmaster May 05 '21 at 13:34

0 Answers0