I have the following response structure which will be serialized following an API call.
public class Details
{
public string firstName { get; set; }
}
public class Result
{
public int maxTry { get; set; }
public int minTry { get; set; }
public List<Details> aggr { get; set; }
public List<string> features { get; set; }
public string zone { get; set; }
}
[Serializable]
public class Root
{
public List<Result> result { get; set; }
}
I have the following array of objects which is an API response.
"result": [
{
“maxTry: 17,
"minTry”: 10,
"details": [
{
“firstName”: “Sam”,
},
{
"firstName”: ”Julio”,
}
],
"aggr": [
“Abc”,
],
"zone": “D3”
},
{
"aggr": [
"Abc",
],
"zone": “C3”
},
{
"aggr": [
"Abc",
],
"zone": “B2”
},
]
}
The problem is even though some objects does not have maxTry
and minTry
property in the response, when I deserialize the response as follows,
var jobject = JsonConvert.DeserializeObject<Root>(res);
I am still getting the output with maxTry
and minTry
defaulted to 0. Can this be instead defaulted to null
CodePudding user response:
Sure, make them nullable ints by putting a question mark after int
[JsonProperty("maxTry")] //newtonsoft
public int? MaxTry { get; set; }
[JsonProperty("minTry")]
public int? MinTry { get; set; }
The JsonProperty attribute let's you name your c# property differently to the json, so you can keep c# naming conventions regardless what the json looks like. If you use System.Text.Json it's JsonPropertyName instead
The reason why your ints are coming out as 0 is that ints are value types, which essentially means they must have a value and cannot be null. The default value for an int is 0; even if you never set a value for MaxTry it would have a value of 0
var r = new Result();
Console.WriteLine(r.MaxTry); //prints 0
Nullable ints are harder to work with, because they might be null; you'll need to check if(r.MaxTry.HasValue)
if you want to see if it's null or not before you do some things with them. To some degree you might want to reconsider leaving them as ints and treating 0 as them having been absent. It might work quite well for your context for example:
for(int try = 0; try < result.MaxTry; try )
This won't run if MaxTry is 0.. if that's a problem then you need to decide if maxtry being 0 is ever valid and if it's not, provide some other sensible default if it is 0
CodePudding user response:
Change those properties to nullable int
public int? maxTry { get; set; }
public int? minTry { get; set; }