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

Time:05-24

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?

CodePudding user response:

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.

CodePudding user response:

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>>();
  • Related