Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether json object has some property

Tags:

json

c#

In Java there is a nice method has that makes it possible to check whether a json object contains a key or not. I use it like so:

JSONObject obj = ....; // <- got by some procedure
if(obj.has("some_key")){
    // do something
}

I could not find the same cool functionality in newtonsoft.json library for C#. So, I wonder what are the alternatives. Thanks!

like image 560
Jacobian Avatar asked Nov 04 '15 09:11

Jacobian


2 Answers

Just use obj["proprty_name"]. If the property doesn't exist, it returns null

if(obj["proprty_name"] != null){
    // do something
}
like image 57
Maraboc Avatar answered Sep 30 '22 00:09

Maraboc


You can try like this:

IDictionary<string, JToken> dict = x;
if (dict.ContainsKey("some_key"))

since JSONObject implements IDictionary<string, JToken>. You can refer MSDN for details

like image 33
Rahul Tripathi Avatar answered Sep 30 '22 01:09

Rahul Tripathi