簡體   English   中英

c#解析json值,檢查是否為空

[英]c# parse json value, check if null

所以我有這個 Web API,它調用一個服務,該服務又返回一個 json 字符串。 字符串看起來有點像這樣:

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

我已經大大減少了這一點,以便更容易地看到我的問題。

當我進行 API 調用時,我使用工廠方法來分解響應,看起來像這樣:

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

現在,如您所見,我正在獲取我的配置器屬性,然后檢查它是否為空。 json 字符串將配置器顯示為null ,但是當我在檢查上放置斷點時,它實際上將其值顯示為{} 我的問題是如何讓它顯示值(空)而不是這個括號響應?

您要求與configurator鍵關聯的JToken 這樣一個令牌-這是一個空令牌。

您可以通過以下方式檢查:

if (configurator.Type == JTokenType.Null)

所以,如果你想扔無論是否有明確的null令牌configurator並沒有在所有被指定,你可以使用:

if (configurator == null || configurator.Type == JTokenType.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為空。

對於那些在較新的 .Net 版本(例如 .Net 5)中使用System.Text.Json人:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM