Created
June 15, 2021 00:01
-
-
Save jbollman7/5af2e95c990814789ea97b947e95e7d8 to your computer and use it in GitHub Desktop.
Deserializing Json 2 .net object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//2 Scenarios. Either returning a list of json objects you can deserailze to .net objects | |
// OR returning a single json object, but the first property of the object is a list, and inside the list is the value you actually want. | |
HttpResponseMessage response = await client.GetAsync(targeturl); | |
response = await client.GetAsync(finalRequestUri); | |
var content = response.Content; | |
// ... Read the string. | |
string json = await content.ReadAsStringAsync(); | |
JObject rss = JObject.Parse(json); | |
//1st scenario; i am returning an array of json objects, that will later be desearilzed. | |
var blockList = new List<storageBlock>(); | |
if (rss.ContainsKey("entries")) | |
{ | |
// ReSharper disable once PossibleNullReferenceException | |
foreach (var e in rss["entries"]) | |
{ | |
var storageBlock = new storageBlock | |
{ | |
ZHostName = zabbixHostName, | |
KeyId = (string)e["content"]["id"], | |
ValueSizeTotal = (string)e["content"]["sizeTotal"] | |
}; | |
ubcList.Add(storageblock); | |
} | |
return blockList; | |
//=================================SCENARIO 2========================================================== | |
//scenario 2 was tougher | |
using HttpClient client = new HttpClient(); | |
var Url = $"https://api.weatherbit.io/v2.0/current/airquality?lat={lat}&lon={lon}&key={APITOKEN}"; | |
HttpResponseMessage response = client.GetAsync(Url).Result; | |
if (response.IsSuccessStatusCode) | |
{ | |
var content = response.Content; | |
var json = content.ReadAsStringAsync().Result; | |
var jsonArray = JsonConvert.DeserializeObject<AQIModel>(json).data.First().aqi; | |
return jsonArray; | |
} | |
// note how i deseralize the single json object to a .net object, and then i access the data property (list type). I call Linq First to grab the value | |
// and then i can grab int property that i want. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment