1

I have a JObject and try to call ToString() on GetValue().

JObject exampleJobject = new JObject();
string text = exampleJObject.GetValue("text").ToString();

If value does not exist it throws an exception. What is the most clever to only call ToString() if the value exist or to return a default value in case the value does not exist?

As a sidenote I want to avoid having to check explicitly for every value if it is null with an if statement before calling ToString().

JObject exampleJobject = new JObject();
JToken value = exampleJObject.GetValue("text");
string text = "";
if(null != value){
    text = value.ToString();
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Noah Ispas
  • 170
  • 2
  • 12
  • 5
    Checking if the value is null? `exampleJObject.GetValue("text")?.ToString()`. – MakePeaceGreatAgain Mar 30 '20 at 10:49
  • You should check value for `null` before getting value, or use [`ConstainsKey`](https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_ContainsKey.htm) method – Pavel Anikhouski Mar 30 '20 at 10:50
  • 1
    For example you could do `exampleJObject.GetValue("text")?.ToString()` and then the default value would be `null` – Ackdari Mar 30 '20 at 10:51
  • 1
    Does this answer your question? [json.net has key method?](https://stackoverflow.com/questions/7216917/json-net-has-key-method) as well as [Possible to look for Key that does not exist in Json.net](https://stackoverflow.com/questions/14544503/possible-to-look-for-key-that-does-not-exist-in-json-net) – Pavel Anikhouski Mar 30 '20 at 10:51

1 Answers1

3

Did you try the following, where we are using the ? to check for nulls in the code after you call GetValue,

JObject exampleJobject = new JObject();
string text = exampleJObject.GetValue("text")?.ToString();

Reference with example code: https://thedotnetguide.com/null-conditional-operator-in-csharp/

Saravanan
  • 7,637
  • 5
  • 41
  • 72