Controllo di JToken vuoto o nullo in un JObject


90

Ho il seguente ...

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

foreach (JObject item in clients.Children())
{
    // etc.. SQL params stuff...
    command.Parameters["@MyParameter"].Value = JTokenToSql(item["thisParameter"]);
}

JTokenToSql Somiglia a questo...

public static object JTokenToSql(JToken obj)
{
    if (obj.Any())
        return (object)obj;
    else
        return (object)DBNull.Value;
}

Ho provato ((JObject)obj).Countanche .. Ma non sembra funzionare.

Risposte:


176

Per verificare se esiste una proprietà su a JObject, è possibile utilizzare la sintassi delle parentesi quadre e vedere se il risultato è nullo o meno. Se la proprietà esiste, JTokenverrà sempre restituito un (anche se ha il valore nullin JSON).

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

Se hai un JTokenin mano e vuoi vedere se non è vuoto, beh, dipende da che tipo JTokenè e da come definisci "vuoto". Di solito utilizzo un metodo di estensione come questo:

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

1
Lo farei metodo di estensione come: public static bool IsNullOrEmpty (questo token JToken) {...} da usare come token JToken = jObject ["param"]; bool empty = token.IsNullOrEmpty ()
Dmitry Pavlov

1
Potrebbe non ToSrtingl' JTokene verificare IsNullOrWhiteSpace? (Dopo aver verificato che JTokennon sia nullo ovviamente)
Coops

1
@CodeBlend That non funzionerà per un oggetto o un array: le versioni serializzate di quelle vuote sono rispettivamente {}e [].
Brian Rogers

1
Vorrei aggiungere il controllo della proprietà: 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) || (token.Type == JTokenType.Property && ((JProperty) token) .Value.ToString () == string.Empty);
jcmontx

59

È possibile procedere come segue per verificare se un valore JToken è nullo

JToken token = jObject["key"];

if(token.Type == JTokenType.Null)
{
    // Do your logic
}

3
Esattamente quello che stavo cercando, a causa di parametri vuoti che restituiscono un tipo nullo che supera un tipico confronto == nullo. Grazie!
Tim Tyler

4

C'è anche un tipo - JTokenType.Undefined.

Questo controllo deve essere incluso nella risposta di @Brian Rogers.

token.Type == JTokenType.Undefined

1

A partire da C # 7 potresti anche usare questo:

if (clientsParsed["objects"] is JArray clients) 
{
    foreach (JObject item in clients.Children())
    {
        if (item["thisParameter"] as JToken itemToken) 
        {
            command.Parameters["@MyParameter"].Value = JTokenToSql(itemToken);
        }
    }
}

L'operatore is controlla il tipo e se lo corregge il valore è all'interno della variabile client.


0

Prova qualcosa di simile per convertire JToken in JArray:

static public JArray convertToJArray(JToken obj)
{
    // if ((obj).Type == JTokenType.Null) --> You can check if it's null here

    if ((obj).Type == JTokenType.Array)
        return (JArray)(obj);
    else
        return new JArray(); // this will return an empty JArray
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.