Reputation: 1279
I have this code that deserializes a JSON string.
Now we can see that the JSON string has for example this property: (Please notice that the CORS property exist under the "has" property so we need to check if "has" also exist before I beleive)
CORS
My question is. Sometimes it do happens that this property could be missing in the JSON string. As seen I use the below code where I use the try/catch block. Because if the CORS property is missing, I get an exception but exceptions are very performance expensive and now I use the try/catch block on 30 properties.
I then wonder how can we check with code if the CORS property exists first? Below line of code WITHOUT try/catch gives this error when CORS does not exist:
Cannot perform runtime binding on a null reference
String corsvalue = "";
try { corsvalue = deserializedTicker.has.CORS.ToLower(); } catch { }
JSON string:
{
"id": "hello",
"name": "Hello",
"has": {
"CORS": false,
"CORS2": true
},
"has2": {
"CORS3": false,
"CORS4": true
}
}
Complete code:
String JSONstring = "{ \"id\": \"hello\", \"name\": \"Hello\", \"has\": { \"CORS\": false, \"CORS2\": true }, \"has2\": { \"CORS3\": false, \"CORS4\": true } }\";"
var deserializedTicker = JsonConvert.DeserializeObject<JsonInfo>(JSONstring);
String corsvalue = "";
try { corsvalue = deserializedTicker.has.CORS.ToLower(); } catch { }
public class JsonInfo
{
public string id { get; set; }
public string name { get; set; }
public JsonHasInfo has { get; set; }
public JsonHas2Info has2 { get; set; }
}
public class JsonHasInfo
{
public bool CORS { get; set; }
public bool CORS2 { get; set; }
}
public class JsonHas2Info
{
public bool CORS3 { get; set; }
public bool CORS4 { get; set; }
}
Upvotes: 1
Views: 4203
Reputation: 4313
Here you go:
String JSONstring = "{ \"id\": \"hello\", \"name\": \"Hello\", \"has\": { \"CORS\": false, \"CORS2\": true }, \"has2\": { \"CORS3\": false, \"CORS4\": true }}";
JObject jobject = JObject.Parse(JSONstring);
JToken cors = jobject.SelectToken("has.CORS");
if (cors != null)
{
JsonInfo myEvent = jobject.ToObject<JsonInfo>();
}
Upvotes: 2