I have an API that accepts a simple class
public class MyPayload
{
public string Id {get;set;}
public JsonElement Payload {get;set;}
}
The Id of the payload tells the backend what class to create and the json Payload is the data to pass along. We are in the process of changing over to this API from basically a scripted solution. Sometimes the data coming in would be in the form of this json:
{
"key":null
}
In the scripted solution we could handle the null pretty simply, and pass back the default value for the provided key. The problem on switching to the API is that "key" has a type, string, or int, or bool but what happens when this is passed into the API I'm getting the following error message:
The JSON value could not be converted to System.Boolean. Path: $.Key | LineNumber: 5 | BytePositionInLine: 38.
One of the things I tried was using [JsonIgnore(Condition = JsonIgnoreCondition.Never)], I actually played with all the ignorecondition options. Basically when "key" == null then "key" was omitted from the output instead of the default value as expected. I've tried several things but as the value is coming in null and not like a type or whatever it's failing.
Ok, I am editing this a little bit as when I originally wrote it I left out I think some vital information, or perhaps wasn't terribly clear. The API references another project that contains the classes that I'm creating via the json payload. These are the classes throwing the error above. For clarity I will post two different versions of said class so you all can see what I've tried.
In the first class below the error is thrown.
public class MyClass
{
public string? Key {get;set;} = "default value";
public bool? IsThing {get;set;} = false;
}
In this instance, the null is passed along, but the default is not used, and there are a few versions of JsonIgnoreCondition where the propery is omitted altogether.
public class MyClass
{
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public string? Key {get;set;} = "default value";
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public bool? IsThing {get;set;} = false;
}
The following updated class follows the old style getter/setter from @ismail. I shortened this to a single property for brevity.
public class MyClass
{
private bool? _IsThing;
public bool? IsThing
{
get
{
if (_IsThing == null)
{
// Default Value
return true;
}
else
{
return _IsThing;
}
}
set
{
if (value == null)
{
// Default Value
_IsThing = true;
}
else
{
_IsThing = value;
}
}
}
}
Thanks for looking!