Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deserialized JSON object not null for wrong type

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading