I'm currently (de-)serializing JSON objects via System.Text.Json (.NET 6), but failing to easily verify if a some of the optional classes are present and if they contain values.
My structure looks like this:
class Request
{
public string RequestID { get; set; }
public User User { get; set; }
...
}
class User
{
public string UserID { get; set; }
public string Username { get; set; }
public bool? SomeOptionalBoolean { get; set; }
}
The JSON object (string) is deserialized to an object that contains the Request
object. However, Request
may not contain a User
object which would raise a NPE when accessing it anyway. Therefore, I'm currently checking each class and its properties for null
values when accessing the object's properties (like request.User.UserID
):
internal static bool IsUserValid(Request request)
{
if (request.User == null || request.User.UserID == null || request.User.Username == null)
{
return false;
}
return true;
}
static void Main(string[] args)
{
if (IsUserValid(request))
{
Console.WriteLine(request.User.UserID);
}
}
This enables me to safely access the required properties, but it seems tedious and there's probably something I'm missing. How can I simplify this approach without writing validations for each and every class?
I've tried to search for solutions (like JsonRequired attributes) in Google and Stack Overflow, but couldn't find a pattern that matches my use case.