Checking if JValue is null

10,978

Solution 1

From my understanding jToken["PurchasedValue"] is a nullable value. You have to use

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

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

Otherwise You can use like

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

This May not even need type casting

Solution 2

You can compare the token type:

var purchasedValueToken = jToken["PurchasedValue"];
int purchasedValue = purchasedValueToken.Type == JTokenType.Null ? 0 : purchasedValueToken.Value<int>();

Solution 3

Well, there are couple of things here :

The jToken["PurchasedValue"] could return anything so a type check would be preferable.

You can change your code as following:

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

Related videos on Youtube

AVEbrahimi
Author by

AVEbrahimi

Untying an impossibly tangled knot is actually possible. For every problem, there is a solution. And I am just one who is interested in untying and solving, that's it :)

Updated on June 04, 2022

Comments

  • AVEbrahimi
    AVEbrahimi about 2 years

    Why this code doesn't run, I want to check if JSON contains integer for key PurchasedValue or not? () :

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

    the error is :

    Error CS0019: Operator `??' cannot be applied to operands of type `method group' and `int' (CS0019) 
    
  • AVEbrahimi
    AVEbrahimi about 7 years
    PurchasedValue = (int)(jToken["PurchasedValue"].Type!=JTokenType.Null ? jToken["PurchasedValue"].Value<int>(): 0);