7

So I have this Web API that calls a service which in turn, returns a json string. The string looks a bit like this:

{
    "title": "Test",
    "slug": "test",
    "collection":{  },
    "catalog_only":{  },
    "configurator":null
}

I have cut this down considerably to make it easier to see my issue.

When I make my API call, I then use a Factory method to factorize the response which looks something like this:

    /// <summary>
    /// Used to create a product response from a JToken
    /// </summary>
    /// <param name="model">The JToken representing the product</param>
    /// <returns>A ProductResponseViewModel</returns>
    public ProductResponseViewModel Create(JToken model)
    {

        // Create our response
        var response = new ProductResponseViewModel()
        {
            Title = model["title"].ToString(),
            Slug = model["slug"].ToString()
        };

        // Get our configurator property
        var configurator = model["configurator"];

        // If the configurator is null
        if (configurator == null)
            throw new ArgumentNullException("Configurator");

        // For each item in our configurator data
        foreach (var item in (JObject)configurator["data"])
        {

            // Get our current option
            var option = item.Value["option"].ToString().ToLower();

            // Assign our configuration values
            if (!response.IsConfigurable) response.IsConfigurable = (option == "configurable");
            if (!response.IsDesignable) response.IsDesignable = (option == "designable");
            if (!response.HasGraphics) response.HasGraphics = (option == "graphics");
            if (!response.HasOptions) response.HasOptions = (option == "options");
            if (!response.HasFonts) response.HasFonts = (option == "fonts");
        }

        // Return our Product response
        return response;
    }
}

Now, as you can see I am getting my configurator property and then checking it to see if it's null. The json string shows the configurator as null, but when I put a breakpoint on the check, it actually shows it's value as {}. My question is how can I get it to show the value (null) as opposed to this bracket response?

3 Answers 3

18

You're asking for the JToken associated with the configurator key. There is such a token - it's a null token.

You can check this with:

if (configurator.Type == JTokenType.Null)

So if you want to throw if either there's an explicit null token or configurator hasn't been specified at all, you could use:

if (configurator == null || configurator.Type == JTokenType.Null)
Sign up to request clarification or add additional context in comments.

Comments

16

For those who use System.Text.Json in newer .Net versions (e.g. .Net 5):

var jsonDocument = JsonDocument.Parse("{ \"configurator\": null }");
var jsonElement = jsonDocument.RootElement.GetProperty("configurator");

if (jsonElement.ValueKind == JsonValueKind.Null)
{
    Console.WriteLine("Property is null.");
}

Comments

0
    public class Collection
    {
    }

    public class CatalogOnly
    {
    }

    public class RootObject
    {
        public string title { get; set; }
        public string slug { get; set; }
        public Collection collection { get; set; }
        public CatalogOnly catalog_only { get; set; }
        public object configurator { get; set; }
    }

    var k = JsonConvert.SerializeObject(new RootObject
                {
                    catalog_only =new CatalogOnly(),
                    collection = new Collection(),
                    configurator =null,
                    slug="Test",
                    title="Test"
                });

    var t = JsonConvert.DeserializeObject<RootObject>(k).configurator;

Here configurator is null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.