Check if JValue is null

Why does this code not run, I want to check if the JSON contains an integer for the key PurchasedValueor not? ():

public PropertyInfo(Newtonsoft.Json.Linq.JToken jToken)
{
    this.jToken = jToken;
    int PurchasedValue = (int)(jToken["PurchasedValue"].Value ?? 0);
}

error:

Error CS0019: Operator `??' cannot be applied to operands of type `method group' and `int' (CS0019) 
+4
source share
2 answers

From my understanding jToken["PurchasedValue"]- a value with a zero value. You have to use

int PurchasedValue = (int)(jToken["PurchasedValue"]?? 0);

nullableObj.Value can be used only without errors only when there is a value for nullableObj

Otherwise, you can use as

int PurchasedValue = jToken["PurchasedValue"].HasValue?jToken["PurchasedValue"].Value: 0;

This May doesn't even require casting

+4
source

Well, there are a couple of things:

jToken ["PurchasedValue"] can return something so that type checking is preferred.

You can change your code as follows:

public PropertyInfo(Newtonsoft.Json.Linq.JToken jToken)
{
    this.jToken = jToken;
    int PurchasedValue = jToken["PurchasedValue"] is int ? jToken["PurchasedValue"] : 0;
}
+4

Source: https://habr.com/ru/post/1675795/


All Articles