Is there a good way to dynamically pass a string variable in place of a deserialized object definition? How I mean, is that the code snippet below is proper syntax to deserialize the JSON response object in order to store the returned data types in a database for further processing.
string inputSymbol = "SNAP";
var client = new RestClient("https://api.tdameritrade.com/v1/marketdata/" + inputSymbol + "/quotes");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer " + ReadAccessToken());
IRestResponse response = client.Execute(request);
dynamic quote = JsonConvert.DeserializeObject(response.Content);
string closePrice = quote.SNAP.closePrice;
string symbol = quote.SNAP.symbol;
string openPrice = quote.SNAP.openPrice;
string highPrice = quote.SNAP.highPrice;
string lowPrice = quote.SNAP.lowPrice;
string lastPrice = quote.SNAP.lastPrice;
string volume = quote.SNAP.totalVolume;
This is a shortened sample JSON response for reference –
{
“SNAP”: {
“symbol”: “SNAP”,
“openPrice”: 56.39,
“highPrice”: 64.44,
“lowPrice”: 55.51,
“closePrice”: 63.64
}
}
For example, I need to specify – quote.SNAP.closePrice – as in the proper syntax above to access the returned closePrice and store in a database.
What I am trying to accomplish, is something more along the lines of the example below for dynamic processing based on the passed variable and not static:
string inputSymbol = "SNAP"; string test = "closePrice"; string closeP = quote + "." + inputSymbol + "." + test;
I’ve tried many different variations through exhaustive testing, but I either get a Cannot perform runtime binding on a null reference, String or binary data would be truncated in table, or ‘string’ does not contain a definition for ‘SNAP’ when trying to convert the response ToString(); None of these error message searches online are applicable to my use case. Any advice would be greatly appreciated.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can deserialize to JObject which has indexer to perform such dynamic querying:
var response = @"{ 'SNAP': { 'symbol': 'SNAP', 'openPrice': 56.39, 'highPrice': 64.44, 'lowPrice': 55.51, 'closePrice': 63.64 } }";
var quote = JsonConvert.DeserializeObject<JObject>(response); // Or JObject.Parse(response)
string inputSymbol = "SNAP";
string test = "closePrice";
string closeP = quote[inputSymbol][test].ToString();
Console.WriteLine(closeP); // prints 63.64
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0