Search code examples
c#jsonasp.net-corejson-deserialization

How I should deserialized this object correctly?


I use an API that return a collection of company symbols with some properties but I don't know how should I deserialize it

{
    "A": {
        "advanced-stats": {
            "prop1": 0.198791,
            "prop2": 16.59,
            "prop3": 12.44,
        }
    },
    "AA": {
        "advanced-stats": {
            "prop1": 0.198791,
            "prop2": 16.59,
            "prop3": 12.44,
        }
    },
    "AAAU": {
        "advanced-stats": {
            "prop1": 0.198791,
            "prop2": 16.59,
            "prop3": 12.44,        
        }
    }
}

Solution

  • You can model the JSON using the following classes:

    public class AdvancedStats
    {
        public double Prop1 { get; set; }
        public double Prop2 { get; set; }
        public double Prop3 { get; set; }
    }
    
    public class AdvancedRoot
    {
        [JsonProperty("advanced-stats")]
        public AdvancedStats AdvancedStats { get; set; }
    }
    

    Since the JSON keys have different names, you can model this as Dictionary<string, AdvancedRoot>. Then to deserialize (using Newtonsoft.Json):

    var results = JsonConvert.DeserializeObject<Dictionary<string, AdvancedRoot>>(json);
    

    Try it online