If i have the following c# record:
public record MyRecord(string EndPoint, string Id);
and i have some json that i attempt to deserialize to my type:
var myType= JsonSerializer.Deserialize<MyRecord>(
jsonStr,
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
}
);
if(myType is null)
{
...
}
where jsonStr is not of type MyRecord but some other type, the resulting myType rather then being null, is simply an instance of MyRecord but with empty properties. How can i check that the returned type is invalid if its not null ?
>Solution :
JsonSerializer does not make assumptions about the lack of contents of a json string, provided that it is at least in the same format as the target structure (e.g. "{ }").
As a result, you need to check one of your properties for validity as well as the object itself:
var jsonStr = "{}";
var myType = JsonSerializer.Deserialize<MyRecord>(
jsonStr,
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
}
);
if (!string.IsNullOrEmpty(myType?.Id))
{
var x = myType;
}
Note that the behavior is identical for classes as well:
public class MyClass
{
public string EndPoint { get; set; }
public string Id { get; set; }
}
var myType2 = JsonSerializer.Deserialize<MyClass>(
jsonStr,
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
}
);
if (!string.IsNullOrEmpty(myType2?.Id))
{
var x = myType;
}