2021年2月11日星期四

Json.net deserialize dictionary and assign dictionary key to dictionary value's member variable

Let's say I have a json like this

"inventory":{    "sh0001":{       "price":100    },    "sh0002":{       "price":50    }  }  

And I want to deserialize it with Json.net, into a data structure like this

class Store  {    public Dictionary<string, Item> inventory;  }  class Item  {    [JsonIgnore] public string id;    public int price;  }  

I want to use the dictionary key (e.g. "sh0001") and assign them to the value object's Id variable (item.id = "sh0001").



One obvious solution is to add a method like Store.OnJsonDeserialized(), and maybe call it within a factory method Store.FromJson(string json), such that we won't forget to and call it after Deserialization...

  public void OnJsonDeserialized()    {       foreach(var kvp in inventory)          kvp.value.id = kvp.key;    }      public static Store FromJson(string json)    {       var newObj = JsonConvert.DeserializeObject<Store>(json);       newObj.OnJsonDeserialized();       return newObj;    }  

But what if we now want to Embed the Store class into another class (e.g. Company), and deserialize that from JSON instead?

class Company  {    public Store[] stores;  }  

Now JsonConvert.DeserializeObject<Company>(json) will not work as intended, and item.Id won't be assigned.

Is there any better way to do the Deserialization in this case? Thank you.

https://stackoverflow.com/questions/66149044/json-net-deserialize-dictionary-and-assign-dictionary-key-to-dictionary-values February 11, 2021 at 01:06PM

没有评论:

发表评论