简体   繁体   中英

c# system.text.json deserialize "different" object to an array of one class

I've a json that have objects like this

"SeasonalInfoBySeasonID": {  
"aa8e0d2d-d29d-4c03-84f0-b0bda96a9fe1": {
                "ID": "aa8e0d2d-d29d-4c03-84f0-b0bda96a9fe1",
                "A": "1",
                "B": 5,
            },
"6f95fb92-5eb2-4fe4-ae01-dc54d810c8a5": {
                "ID": "6f95fb92-5eb2-4fe4-ae01-dc54d810c8a5",
                "A": "1",
                "B": 5,
            }, .....
}

the objects of SeasonalInfoBySeasonID are clearly all of the same data structure, but unfortunately they aren't even listed in an array, and instead of listing them one by one in seasoninfobyseasonid model I'm using doing this:

public class SeasonalInfoBySeasonID
    {
        private IDictionary<string, object> _additionalProperties = new Dictionary<string, object>();

        [JsonExtensionData]
        public IDictionary<string, object> AdditionalProperties
        {
            get { return _additionalProperties; }
            set { _additionalProperties = value; }
        }
    }

works great, but I was wondering is it possible to de-serialize such an object with multiple objects of the "same type", to an array directly?

You don't need the class at all.

You can just declare the property on the root object like this

public Dictionary <string, YourType> SeasonalInfoBySeasonID {get;set;} = new Dictionary <string, YourType>();

Then each key will be aa8e0d2d-d29d-4c03-84f0-b0bda96a9fe1 etc., and the objects will be the inner type.

you can convert your data to a list

    using Newtonsoft.Json;

    var jsonObject = JObject.Parse(json);

    List<Item> list = ((JObject)jsonObject["SeasonalInfoBySeasonID"]).Properties()
                      .Select(p => p.Value.ToObject<Item>()).ToList();

public class Item
{
    public string ID { get; set; }
    public string A { get; set; }
    public int B { get; set; }
}

result

[
  {
    "ID": "aa8e0d2d-d29d-4c03-84f0-b0bda96a9fe1",
    "A": "1",
    "B": 5
  },
  {
    "ID": "6f95fb92-5eb2-4fe4-ae01-dc54d810c8a5",
    "A": "1",
    "B": 5
  }
]

or you can use a dictionary

Dictionary<string,Item> SeasonalInfoBySeasonID = 
Object.Parse(json)["SeasonalInfoBySeasonID"]
.ToObject<Dictionary<string, Item>>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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