I was working on a section of this code that is grabbing api data. In it I'm taking the json file and reading to a string into json.net to deserialize and put parts of the data into an object class. The way the json reads is a list of Result objects. I have gotten the count from the root method but I am having problems getting data from the list of Result objects.
Object classes
public class Result
{
public string id { get; set; }
public string status { get; set; }
}
public class WarehouseInformation
{
public int count { get; set; }
public List<Result> result { get; set; }
}
orderData is the string of the json file being read in.
{
Console.WriteLine("orderdatatoarray");
WarehouseInformation warehouseInformation = JsonConvert.DeserializeObject<WarehouseInformation>(orderData);
if (warehouseInformation != null)
{
var test = warehouseInformation.count;
string[] orderStringArr = new string[0];
Console.WriteLine(test);
List<Result> idList = new List<Result>();
return orderStringArr;
}
else
{
string[] orderStringArr = new string[0];
return orderStringArr;
}
}
}
The error is: System.NullReferenceException: 'Object reference not set to an instance of an object.'
last is part of the json file I am trying to read from, I doubt this is the issue at fault but I might have missed a way to setup the classes above. json api structure
In Newtonsoft, model binding will take place under 2 circumstances
[JsonProperty("jsonKeyNameHere")]
to specify the exact json field it must bind toAs such in the WarehouseInformation class it should be either
public List<Result> results { get; set; }
[JsonProperty("results")] public List<Result> result { get; set; }
Using either is fine, personally I prefer #2 as it allows you to name your members in line with C# naming practices, and the compiler won't throw you warnings because the naming is non-standard. A bit more work, but it makes for clean code. But if that doesn't matter or you prefer your class members mimic the json keys 1:1, then route #1 is perfectly fine.
In NewtonSoft, json structure dictates the composition patterns of the classes it aims to deserialize to. So this is what you have right now: if WarehouseInformation is seen as a container for the entire Json response, then you are grabbing the "count" field and the "results" json array (which translates to a List), and for each element of "results", you are taking "id" and "status". This composition pattern is right, its just you need the naming of the members to line up to the json keys for proper model binding