2

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,        
        }
    }
}
haldo
  • 14,512
  • 5
  • 46
  • 52
Filip Laurentiu
  • 854
  • 3
  • 9
  • 29
  • This might help you to get a starting point: http://json2csharp.com/ – Stefan Nov 22 '19 at 09:13
  • I already try this method, also on other sites, but nothing match – Filip Laurentiu Nov 22 '19 at 09:14
  • @Stefan You probably don't want to use external web applications as you might store sensitive data somewhere else. You should refrain from using those and OP is asking for a specific C# solution when looking at the tags. – Barrosy Nov 22 '19 at 09:14
  • @Barrosy: well, I meant just to get started with the C# modeling... anyhow, OP seems to already have tried that. – Stefan Nov 22 '19 at 09:15
  • What solutions have you tried so far? Please check [How-to-ask](https://stackoverflow.com/help/how-to-ask) when asking questions. You might want to check out [this](https://stackoverflow.com/questions/7895105/deserialize-json-with-c-sharp) question. See the following method `System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(json);` as reference. – Barrosy Nov 22 '19 at 09:16
  • 1
    Dictionary (keys = A, AA etc) of Objects containing a property (advanced-stats) of type List/Array of “some pair type” would be a start.. and transform in whatever local model is appropriate. – user2864740 Nov 22 '19 at 09:19
  • @user2864740 It seams that this is the way. I also try this method but in a wrong way. Thank you very much ! – Filip Laurentiu Nov 22 '19 at 09:29

1 Answers1

8

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

haldo
  • 14,512
  • 5
  • 46
  • 52