Carlo Chan Carlo Chan - 8 months ago 60
JSON Question

Json deserialization to double type

Can you only deserialize JSON to a string type? What if I am using a double as a range and want my JSON data to point at that range type double like a circular gauge?

Json data im trying to collect:

{
"channel":
{
"id":301726,
"name":"Testing ESP8266",
"description":"Water meter pulse count",
"latitude":"0.0",
"longitude":"0.0",
"field1":"Pulse",
"created_at":"2017-07-12T12:19:38Z",
"updated_at":"2017-1003T06:14:29Z",
"elevation":"54",
"last_entry_id":531
},
"feeds": [
{
"created_at":"2017-1002T21:56:57Z",
"entry_id":432,
"field1":"16.00" },
{
"created_at":"2017-1002T21:57:17Z",
"entry_id":433,
"field1":"16.00" }
]

}

Answer Source

First, create suitably classes

public class Channel
    {
        public int id { get; set; }
        public string name { get; set; }

        // and so on

    }
    public class Feeds
    {
        public DateTime created_at { get; set; }
        public int entry_id { get; set; }
        public double field1 { get; set; }
    }

then parse the JSON

public static void parseJson()
    {
        using (WebClient wc = new WebClient())
        {
            var json = wc.DownloadString(@"https://thingspeak.com/channels/301726/field/1.json");
            JObject obj = JObject.Parse(json);
            foreach (var feedObj in obj["feeds"])
             {
                 Feeds feed = JsonConvert.DeserializeObject<Feeds>(feedObj .ToString());
                 double feild1 = feed.field1;
             }
        }
    } 

now you have feild1 as a double and you can use it

EDIT: an answer with HttpClient

static HttpClient _client = new HttpClient();

public static async Task<Feeds> getJson()
    {
        using (var response = await _client.GetAsync("https://thingspeak.com/channels/301726/field/1.json"))
        {
            if (response.IsSuccessStatusCode)  {

                var json = await response.Content.ReadAsStringAsync();
                JObject obj = JObject.Parse(json);
                Feeds feed = null;
                foreach (var feedObj in obj["feeds"])
                {
                    feed = JsonConvert.DeserializeObject<Feeds>(feedObj.ToString());
                    double feild1 = feed.field1;
                }
                return feed;
            }
        }

        return null;
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download