c解析json值,检查是否为null

本文关键字:是否 null 检查 解析 json | 更新日期: 2023-09-27 17:54:03

所以我有了这个Web API,它调用一个服务,然后返回一个json字符串。字符串看起来有点像:

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

为了更容易看到我的问题,我已经大幅减少了这一点。

当我进行API调用时,我使用Factory方法对响应进行因子分解,如下所示:

    /// <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;
    }
}

现在,正如您所看到的,我正在获取配置器属性,然后检查它是否为null。json字符串将配置器显示为null,但当我在检查中设置断点时,它实际上将其值显示为{}。我的问题是,如何让它显示值(null(,而不是这个括号响应?

c解析json值,检查是否为null

您正在请求与configurator键关联的JToken就是这样一个令牌-它是一个空令牌。

您可以使用进行检查

if (configurator.Type == JTokenType.Null)

因此,如果存在显式null令牌或根本没有指定configurator,则您可以使用:

if (configurator == null || configurator.Type == JTokenType.Null)

适用于在更新版本中使用System.Text.Json的用户。网络版本(例如.Net 5(:

var jsonDocument = JsonDocument.Parse("{ '"configurator'": null }");
var jsonElement = jsonDocument.RootElement.GetProperty("configurator");
if (jsonElement.ValueKind == JsonValueKind.Null)
{
    Console.WriteLine("Property is null.");
}
    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;

此处configurator为空。