Robert Segdewick
Robert Segdewick

Reputation: 593

converting json bool values to C# bool values

I ma trying to convert json boolean value string to C# equivalent. This is my code:

  string jsonResponseString = "{boolvalue:'true'}";
  dynamic jsonResponse = JsonConvert.DeserializeObject(jsonResponseString);

  if (jsonResponse.boolvalue == true){
    Console.WriteLine("yes it is bool");
  }
  else{
    Console.WriteLine("no it is still a string");
  }

Unfortunately, boolvalue remains string "true" and not bool true. Since I will not know at runtime what kind of obkect string I am getting, I'd like to awoid explicit typecasting with DeserializeObject<type>. I feel like I am missing something obvious. What is the correct way of converting string bools to actual bool values?

Upvotes: 0

Views: 1532

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

The json value in your JSON string is literally the string true. For it to be parsed as a bool, you should declare it as a bool by removing the quotes:

string jsonResponseString = "{boolvalue: true}";

Upvotes: 5

Related Questions