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?
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}";
Related
I am trying to check if value exists in a string array. The below one works but when I tried the next code block, it failed.
bool exixts;
string toCheck= "jupiter";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck))
{
exists = true;
}
How can I check for trim and case sensitivity?
I tried this
bool exixts;
string toCheck= "jupiter ";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
{
exists = true;
}
The IEnumerable<string>.Contains(value, comparer) expects a compare class instance, not an enum value.
The library does have some ready made comparers available though:
//if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
if (printer.Contains(toCheck.Trim(), StringComparer.OrdinalIgnoreCase))
Or you can do like this,
bool exists = printer.Any(x=> x == toCheck.Trim());
Hope helps,
I have the following code:
bool SilentUpdate { get; set;}
....
string temp = "";
SilentUpdate = Convert.ToBoolean(temp ?? "false");
I want to default SilentUpdate to false when temp string is empty. The above code still issue error "String was not recognized as a valid Boolean."
How can I do that?
This is slightly diffrent logic, but this will give you false for any value that does not correctly convert in to a Boolean which is likely what you are really looking for.
string temp = "";
bool result
if(!bool.TryParse(temp, out result))
{
result = false; //This line and the `if` is not actually necessary,
//result will be false if the parse fails.
}
SilentUpdate = result;
Using Convert.ToBoolean the string being parsed must either be a Boolean.TrueString, Boolean.FalseString or null. If it's any other value, then an exception will be thrown, so you must ensure to add a try...catch around the conversion code, example:
string temp = "nope";
SilentUpdate = Convert.ToBoolean(temp); // Exception: "String is not recognized as a valid Boolean"
Using Boolean.TryParse you can alleviate this, as well as get a default value as you're wanting:
string temp = "";
bool res = false;
SilentUpdate = (Boolean.TryParse(temp, out res) ? res : false);
Boolean.TryParse returns true or false if the parse succeeded and if it succeeded the ternary logic returns what was parsed, otherwise it's false.
Hope that can help.
You can use Boolean.TryParse() method as well. It returns bool based on whether the parsing has succeeded or not.
bool flag;
if (Boolean.TryParse(temp, out flag))
The code should be:
SilentUpdate = Convert.ToBoolean(string.IsNullOrEmpty(temp) ? "false" : temp)
You're misusing the ?? operator in your code. It only returns the second operand if the first one is null, not falsy. Empty string is not null and therefore temp ?? "false" returns the empty string, which is not a valid boolean value.
How can I get the value of a specific nested property, from a JSON object, at runtime?
Here is an example that ilustrates what I am trying to do (without error checking, because it's just a quick example):
JSON Object:
string jsonobj = "{
"Header":"someHeader",
"FirstNest":{
"Property1":"123",
"property2":"321",
"SecondNest":{
"property3":"456",
"property4":"789"
}
}
In my code, I would have something like this :
string read = Console.ReadLine();
where the user will input, for example FirstNest.Property1 and then I would return 123. I could do something like this:
JObject msg = JObject.Parse(jsonobj);
string[] tosearch = read.Split('.'); // This would give me FirstNest Property1
string tofind = (string)msg[tosearch[0]][tosearch[1]];
The problem arises when the user wants to access FirstNest.SecondNest.property3, because my hard-coded method can only take two strings. How can I build such a "query" method at runtime, with which I could enable the user to search for any property?
One soultion would be to make a function
GetProperty(JObject msg, string str1, string str2)
{
return (string)msg[str1][str2];
}
then another one , which would take 3 strings as input :
GetProperty(JObject msg, string str1, string str2, string str3)
{
return (string)msg[str1][str2][str3];
}
, then another one, which would take 4 strings as input, and so on... which doesn't seem like an efficient solution.
How about this (exception handling excluded for brevity):
public string GetJsonPropertyValue(string json, string query)
{
JToken token = JObject.Parse(json);
foreach(string queryComponent in query.Split('.'))
{
token = token[queryComponent];
}
return token.ToString();
}
Given the json in your example a search for this FirstNest.SecondNest.property3 will return 456. You should include any necessary user input validation and exception handling.
I am facing quite an odd issue,....
I have got a code which reads XML and converts each value irrespective of what type it is for example, int, float, double or a String it self to a String value and then stores it into a String variable.
String column = System.Convert.ToString(values.GetValue(rowNum, colNum))
problem I have is, lets say if "values.GetValue(rowNum, colNum)" returns 0.000003825, then when ran, the value that gets converted and stored in "column" is "3.825E-06" which is in scientific notation which I do not really want,
I want "column" to store value 0.000003825 in string format, how do I do that?
thanks
You will need to supply formatting information. Unfortunately, you can't supply formatting information to System.Convert.ToString(). Instead, you must call string.Format() or object.ToString().
For example:
double value = 0.000003825;
string s1 = value.ToString("0.################");
Console.WriteLine(s1);
string s2 = string.Format("{0:0.################}", value);
Console.WriteLine(s2);
Try ToString() to convert it to object
OK, I have fixed this now..
It works a treat irrespective of what the type of value we pass through obj,
thanks.
Object obj = -0.00002357467;
String value = obj.ToString();
String type = obj.GetType().ToString();
if (type.Equals("System.Double")&&value.Contains("E-"))
{
double doubleValue = (double)obj;
value = doubleValue.ToString("0.############################"); //thanks #Matthew Watson
}
Console.WriteLine(value); //prints -0.00002357467
This question already has answers here:
Not able to cast string to int. Error msg: Input string was not in a correct format
(6 answers)
Closed 9 years ago.
if (!IsPostBack)
{
string EnquiryID = (Session["Enq_ID"].ToString());
if (EnquiryID != null)
{
int Enquiry = Convert.ToInt32(EnquiryID);
hotelOBJ.FillbyQueryEnquiry1(Enquiry, txtClientph, txtClientAddress );
}
}
there is my code my session is not convert into integer the error is
"Input string was not in a correct format. "
The error says that there might be some characters that can't be converted to Integer in any case like 1234ab contains characters ab which can't be converted to Integer.
What you can do is:
bool result = Int32.TryParse(Session["Enq_ID"].ToString(), out number);
if (result)
{
hotelOBJ.FillbyQueryEnquiry1(number, txtClientph, txtClientAddress );
}
else
{
Console.WriteLine("Attempted conversion of '{0}' failed.",
Session["Enq_ID"].ToString());
}
I think the string that you try to convert to int is empty or it contains characters that is not digits (basically your string does not represent an integer value in a string form). That's why you get that error message.
So at least you have to replace your
if (EnquiryID != null)
with
if(!string.IsNullOrWhiteSpace(EnquiryID))
That's how you will know what if you try to convert variable it at least have something to convert.
And or use Int32.TryParse() function to test (and convert to integer) if the string that you try to convert is an integer.
Use Int32.Parse(). Beware FormatException when parsing, its good to use TryParse first or wrap TryParse in an extension method. Also change your if statement. The way you have it now can result in NullReferenceException if your query string parameter is missing.
if (!IsPostBack)
{
if (Session["Enq_ID"] != null)
{
string EnquiryID = Session["Enq_ID"].ToString();
if (EnquiryID.IsValidInt32())
{
int Enquiry =Int32.Parse(EnquiryID);
hotelOBJ.FillbyQueryEnquiry1(Enquiry, txtClientph, txtClientAddress );
}
}
}
Extension method...
public static bool IsValidInt32(this string value)
{
int result;
return int.TryParse(value, out result);
}