0

I am currently trying to parse the JSON data that I get back from the IEX api, which consists of stocks and their information. The problem I am running into is that depending on which stocks/symbols (ie AAPL, GOOGL etc) you request the keys that are returned change to that symbol. An example of the returned JSON can be seen here: https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,fb,googl&types=quote,chart&range=1m

To deserialize this I am using JSON.NET and the following classes:

public class Stock  {
    public quote Quote { get; set;}
    public chart Chart { get; set;}
}

public class Root {
    public Stock[] Stock;
}

And then I also have classes for the quote and chart objects. I then deserialize the JSON using:

var stocks =  JsonConvert.DeserializeObject<Root>(jsonstring);

However, this does not work, but this does work when renaming the 'Stock' class to one of the symbol names, but then only that symbols JSON is parsed. I have no idea what's going on here so any help is greatly appreciated!

6
  • Since you're using iextrading, have you considered using a library already built so that you don't have to build structures? see codepoc.io/blog/web-api/5297/… Commented Dec 12, 2018 at 21:05
  • You can create your classes like follows: public class AAPL { [JsonProperty("quote")] public Quote Quote; } public class Root { [JsonProperty("AAPL")] public AAPL Appl; } public class Quote { [JsonProperty("symbol")] public string Symbol; // other properties .. } Commented Dec 12, 2018 at 21:59
  • The method which gets the data from your API: static async Task<String> getStocks() { HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync("api.iextrading.com/1.0/stock/market/…); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); return responseBody; } Commented Dec 12, 2018 at 22:00
  • I've created a simple console app, you can make conversion like this in the Main method: static void Main(string[] args) { var data = getStocks().GetAwaiter().GetResult(); var res = JsonConvert.DeserializeObject<Root>(data); // another method to get deserialized data dynamic stuff = JsonConvert.DeserializeObject(data); var obj1 = stuff.AAPL; var obj2 = stuff.AAPL.quote; var obj3 = stuff.AAPL.quote.symbol; } Commented Dec 12, 2018 at 22:02

1 Answer 1

2

Your problem is that your class models don't match the json schema of the API output. The output isn't a list of stocks, it is a mapping of StockName: Stock

You can deserialize it as a Dictionary<string, Stock> rather than a Root and that should get you where you need to be.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.