I have a json feed which I am trying to deserialize:
{
"d": [
{
"__type": "Status:http://jdlf.com.au/ns/business/api",
"countedAbsence": false,
"description": "",
"name": "Not Marked",
"schoolSystemExportIdentifier": "0",
"shortCode": "-",
"shortName": "Not Marked",
"statusId": "802b325b-8ab6-4c84-b782-3e376024d4a7"
},
{
"__type": "Status:http://jdlf.com.au/ns/business/api",
"countedAbsence": false,
"description": "Student is considered to be attending(DoE 'Present In Class' Status)",
"name": "Present",
"schoolSystemExportIdentifier": "100",
"shortCode": "P",
"shortName": "Present",
"statusId": "00205dad-44c6-405e-9958-451a7d0b5194"
}
]
}
After I deserialize the received string stream I just want to output the name element in a simple for loop.
I have no idea what I doing wrong as dtoDirectiries is always returning null.
I have tried changing
var dtoDirectiries = SerializerHelper.Deserialize<List<Statuses>>(output);
to
List<Statuses> dtoDirectiries = SerializerHelper.Deserialize<List<Statuses>>(output);
with no change.
Thanks in advance for your help.
Michael
using CompassAPI;
using Newtonsoft.Json;
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "{Removed for security}");
request.Headers.Add("CompassApiKey", "{removed for security}");
request.Headers.Add("Cookie", "{removed for security}");
var content = new StringContent("{\"schoolSystemType\": \"aus\"}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string output = await response.Content.ReadAsStringAsync();
Console.WriteLine(output);
var dtoDirectiries = SerializerHelper.Deserialize<List<Statuses>>(output);
for (int i = 0; i < dtoDirectiries.Count; i++)
{
Console.WriteLine(dtoDirectiries[i].name);
}
Console.ReadLine();
public class Statuses
{
[JsonProperty("__type")]
public string __type { get; set; }
[JsonProperty("countedAbsence")]
public string countedAbsence { get; set; }
[JsonProperty("description")]
public string description { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("schoolSystemExportIdentifier")]
public string schoolSystemExportIdentifier { get; set; }
[JsonProperty("shortCode")]
public string shortCode { get; set; }
[JsonProperty("shortName")]
public string shortName { get; set; }
[JsonProperty("statusId")]
public string statusId { get; set; }
}
>Solution :
The problem is your JSON response is an object. You need to extract the data from d property.
Either working with Newtonsoft.Json.Linq to extract the data ind property:
using Newtonsoft.Json.Linq;
var dtoDirectiries = JObject.Parse(output)
.SelectToken("d")
.ToObject<List<Statuses>>();
Or create a Root class and deserialize as Root instance:
var dtoDirectiries = JsonConvert.DeserializeObject<Root>(output)
.Data;
public class Root
{
[JsonProperty("d")]
public List<Statuses> Data { get; set; }
}