Dattatray Deokar
Dattatray Deokar

Reputation: 2103

how to check JsonObject has null value(windows.data.json)

How can I check if any key from json object have null value

  JsonObject itemObject = itemValue.GetObject();   

  string id = itemObject["id"].GetString() == null ? "" : itemObject["id"].GetString();

  this is my code but app crashes on it if null value for key "id"

Upvotes: 2

Views: 9309

Answers (4)

kiewic
kiewic

Reputation: 16420

IJsonValue idValue = itemObject.GetNamedValue("id");

if ( idValue.ValueType == JsonValueType.Null)
{
    // is Null
}
else if (idValue.ValueType == JsonValueType.String)
{
    string id = idValue.GetString();
}

If you do this too much, consider adding extension methods.

To do the opposite use:

IJsonValue value = JsonValue.CreateNullValue();

Read here more about null values.

Upvotes: 4

Dattatray Deokar
Dattatray Deokar

Reputation: 2103

Here is solution for the issue

string id = itemObject["id"].ValueType == JsonValueType.Null ? "" : itemObject["id"].GetString();

Upvotes: 0

Dead.Rabit
Dead.Rabit

Reputation: 1975

if itemObject["id"] is null then the method null.GetString() doesn't exist and you'll get the error specified (null object never has any methods/fields/properties).

string id = itemObject["id"] == null ? (string)null : itemObject["id"].GetString(); // (string)null is an alternative to "", both are valid null representations for a string, but you should use whichever is your preference consistently to avoid errors further down the line

the above avoids calling .GetString() until you've asserted that the ID isn't null (check here for more in-depth), if you're using C#6 you should be able to use the new shorthand:

string id = itemObject["id"]?.GetString();

Upvotes: 0

Cassian
Cassian

Reputation: 3738

http://msdn.microsoft.com/en-us/library/ms173224.aspx

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

Upvotes: 0

Related Questions