Checking for empty or null JToken in a JObject

后端 未结 5 1123
忘了有多久
忘了有多久 2020-12-04 17:23

I have the following...

JArray clients = (JArray)clientsParsed[\"objects\"];

foreach (JObject item in clients.Children())
{
    // etc.. SQL params stuff...         


        
5条回答
  •  盖世英雄少女心
    2020-12-04 17:42

    To check whether a property exists on a JObject, you can use the square bracket syntax and see whether the result is null or not. If the property exists, a JToken will be always be returned (even if it has the value null in the JSON).

    JToken token = jObject["param"];
    if (token != null)
    {
        // the "param" property exists
    }
    

    If you have a JToken in hand and you want to see if it is non-empty, well, that depends on what type of JToken it is and how you define "empty". I usually use an extension method like this:

    public static class JsonExtensions
    {
        public static bool IsNullOrEmpty(this JToken token)
        {
            return (token == null) ||
                   (token.Type == JTokenType.Array && !token.HasValues) ||
                   (token.Type == JTokenType.Object && !token.HasValues) ||
                   (token.Type == JTokenType.String && token.ToString() == String.Empty) ||
                   (token.Type == JTokenType.Null);
        }
    }
    

提交回复
热议问题