Daniel Anderson Daniel Anderson - 1 year ago 109
ASP.NET (C#) Question

Struggling to convert JSON string into an object

I am struggling with how to convert the following price quote JSON data into a C#

{"@name":"3M Corp","low":"194.80","high":"136.78","change":"2.80","pctchange":"0.22","ask":"135.15","bid_time":"20161104131845","bid":"134.80"}

I created a C# class like so:

public class Quote
public string Provider { get; set; }
public Data Info { get; set; }

public class Data
public string name { get; set; }
public decimal low { get; set; }
public decimal high { get; set; }
public decimal change { get; set; }
public decimal pctchange { get; set; }
public decimal ask { get; set; }
public DateTime bid_time { get; set; }
public decimal bid { get; set; }

Then, in code, I am fetching the data using an
, which runs just fine. But the step to deserialize the JSON data doesn't work.. It doesn't throw an error, it just has no data. That code is:

var request = HttpWebRequest.Create(new Uri("<request URL here>")) as HttpWebRequest;
request.Method = "POST";
var response = request.GetResponse();
using (Stream stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
Quote quote = JsonConvert.DeserializeObject<Quote>(reader.ReadToEnd());
lblPrice.Text = string.Format("{0:c}", quote.Data.ask);

I stepped through the code, so I know the web request is working and returning a JSON string. I just don't know how to structure the C# class to accept the deserialized data. Help would be appreciated!

Answer Source

have you tried to use this json2csharp

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download