Input string 'x' is not a valid number error with JsonConvertDeserializeObject - c#

I have a string for billingpostalcode. When you enter pure numbers on it ex: '12345' then it is working fine. But for example you put '123aa' or 'abcde' it is producing an exception. It is a string and not an integer so i don't understand the error.
{"Unexpected character encountered while parsing number: s. Path 'billingPostalCode', line 1, position 119."}
string billingPostal = billingPostalCode;
var obj = JsonConvert.DeserializeObject($"{{ 'odrDetailHdr' : {orderDetailHeaderJson}, 'billingPostalCode' : {billingPostal}, 'odrProductList': {orderTrackingDetailsProductJson}, 'odrDetailOtherHdr': {orderDetailOtherHeaderJson} }}");
Anyone has an idea why?

There is different notation between a string and a number in the json format.
"employee":{ "name":"John", "age":30, "city":"New York" }
Notice the difference between the string "name":"John"and the number "age":30, They are not interchangeable
However, in your example you could add the quotes, or use a converter via an attribute when using json.net

Related

Input string was not in correct format error when parsing to int

I get error "Input string was not in correct format" when parsing to int.
But string is in correct format. I'm adding screenshot below.
The problem is that there must be some hidden characters in your a string variable (Carriage Return maybe?). Try int.Parse(a.Substring 0,4) as usually they are at the end of the string.
You could also clean the input where you are getting that value from.
I noticed you are doing multiple conversions. Are you sure it's a ("2016") that is causing the error?
if yes, then there must be hidden characters as other have suggested. The a.substring(0,4) would indeed remove any trailing characters. But if the first character is a hidden char, it would not.
string output = new string(input.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
should clear out any possible hidden characters.
Maybe you can try something like this:
int x = Convert.ToInt32(a);
Furthermore you can try to use the .ToString() Methode of a to make it run more stable.
You can additionaly try to clear the string from all "non number" chars using Rexex:
/// <summary>
/// RegEx to extract all non numeric values.
/// </summary>
private static readonly Regex rxNonDigits = new Regex(#"[^\d.,-]+");
Use it as follows to clear:
String a2 = rxNonDigits.Replace(a, "");
I think you are using REST API with JSON or passing whole string in query string i.e JSON formatted string, then you should use
a = new JavaScriptSerializer().Deserialize(a, null).ToString();
x = int.Parse(a);

Read input with different datatypes and space seperation

I'm trying to figure out how to write code to let the user input three values (string, int, int) in one line with space to separate the values.
I thought of doing it with String.Split Method but that only works if all the values have the same datatype.
How can I do it with different datatypes?
For example:
The user might want to input
Hello 23 54
I'm using console application C#
Well the first problem is that you need to decide whether the text the user enters itself can contain spaces. For example, is the following allowed?
Hello World, it's me 08 15
In that case, String.Split will not really be helpful.
What I'd try is using a regular expression. The following may serve as a starting point:
Match m = Regex.Match(input, #"^(?<text>.+) (?<num1>(\+|\-)?\d+) (?<num2>(\+|\-)?\d+)$");
if (m.Success)
{
string stringValue = m.Groups["text"].Value;
int num1 = Convert.ToInt32(m.Groups["num1"].Value);
int num2 = Convert.ToInt32(m.Groups["num2"].Value);
}
BTW: The following part of your question makes me frown:
I thought of doing it with String.Split Method but that only works if all the values have the same datatype.
A string is always just a string. Whether it contains a text, your email-address or your bank account balance. It is always just a series of characters. The notion that the string contains a number is just your interpretation!
So from a program's point of view, the string you gave is a series of characters. And for splitting that it doesn't matter at all what the real semantics of the content are.
That's why the splitting part is separate from the conversion part. You need to tell your application that that the first part is a string, the second and third parts however are supposed to be numbers. That's what you need type conversions for.
You are confusing things. A string is either null, empty or contains a sequence of characters. It never contains other data types. However, it might contain parts that could be interpreted as numbers, dates, colors etc... (but they are still strings). "123" is not an int! It is a string containing a number.
In order to extract these pieces you need to do two things:
Split the string into several string parts.
Convert string parts that are supposed to represent whole numbers into a the int type (=System.Int32).
string input = "Abc 123 456"
string[] parts = input.Split(); //Whitespaces are assumed as separators by default.
if (parts.Count == 3) {
Console.WriteLine("The text is \"{0}\"", parts[0]);
int n1;
if (Int32.TryParse(parts[1], out n1)) {
Console.WriteLine("The 1st number is {0}", n1);
} else {
Console.WriteLine("The second part is supposed to be a whole number.");
}
int n2;
if (Int32.TryParse(parts[2], out n2)) {
Console.WriteLine("The 2nd number is {0}", n2);
} else {
Console.WriteLine("The third part is supposed to be a whole number.");
}
} else {
Console.WriteLine("You must enter three parts separated by a space.");
}
What you have to do is get "Hello 23 54" in a string variable. Split by " " and treat them.
string value = "Hello 23 54";
var listValues = value.Split(' ').ToList();
After that you have to parse each item from listValues to your related types.
Hope it helps. ;)

Input string is not in correct format?

Ok, hey. I made a program for an in-game.. game. And I have it load data for a player from their own .txt on my computer. Whenever i try to command (.load) it tells me (at split[1] where it is converted to an int32) which is just a test to see if your bombs load, input string is not in correct format, heres the code:
StreamReader streemy = new StreamReader(#"c:\Usernames\" + player[m.GetInt(0)].username + ".txt");
string read = streemy.ReadToEnd();
if (!string.IsNullOrEmpty(read))
{
string[] split = read.Split('=');
player[m.GetInt(0)].bombs = Convert.ToInt32(split[1]);
Say(names[m.GetInt(0)].ToUpper() + ": You data has been loaded!");
streemy.Close();
}
else
{
Say(names[m.GetInt(0)].ToUpper() + ": Your data was empty :( Say '.save' to save your current data!");
}
.save Saves the data to the .txt, "names[m.GetInt(0)]" is their username, Say just tells them in the game the message. Thanks for your help! PS: player is a struct, which has ints like bombs.
I would suggest you to use Int32.TryParse instead of Convert.ToInt32.
So if the value is not valid integer then you can treat as 0 or no bomb.
int numberOfBombs = 0;
bool result = Int32.TryParse(value, out numberOfBombs);
now numberOfBombs would retain the actual value if there is valid integer field present otherwise it will be 0.
You must be getting a FormatException.
FormatException is thrown when the arguement is not in valid format.
I think that the value of split[1] is not a valid integer.
According to msdn.
FormatException : value does not consist of an optional sign followed by a sequence of digits (0 through 9).
Using the ToInt32(string) method is equivalent to passing value to the Int32.Parse(String) method. value is interpreted by using the formatting conventions of the current thread culture.
You can call the Int32.TryParse method instead. It returns a Boolean value that indicates whether the conversion succeeded or failed.

using strings in c#.net

Hi How do I retrieve the number from the following string,
{"number":100,"data":[test]}
The number could be of any length.
I used the following code. but it gives and error message
strValue.Substring((strValue.IndexOf(":")+1), (strValue.IndexOf("data")));
the output comes like
100,"data":[
Thanks,
It looks like your input string is JSON. Is it? If so, you should use a proper JSON parser library like JSON.NET
As noted by Jon, your input string seems to be a JSON string which needs to be deserialized. You can write your own deserializer, or use an existing library, such as Json.NET. Here is an example:
string json = #"[
{
""Name"": ""Product 1"",
""ExpiryDate"": ""\/Date(978048000000)\/"",
""Price"": 99.95,
""Sizes"": null
},
{
""Name"": ""Product 2"",
""ExpiryDate"": ""\/Date(1248998400000)\/"",
""Price"": 12.50,
""Sizes"": null
}
]";
List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
Your attempt is close. There are two (possibly three issues) I found.
Your string has a comma after the number you're looking for. Since your code is searching for the index of "data", your end index will end up one character too far.
The second paramter of String.Substring(int, int) is actually a length, not an end index.
Strings are immutable in C#. Because of this, none of the member functions on a string actually modify its value. Instead, they return a new value. I don't know if your code example is complete, so you may be assigning the return value of SubString to something, but if you're not, the end result is that strValue remains unchanged.
Overall, the result of your current call to string.Substring is returning 100,"data":[tes. (and as far as I can see, it's not storing the result).
Try the following code:
string justTheNumber = null;
// Make sure we get the correct ':'
int startIndex = strValue.IndexOf("\"number\":") + 9;
// Search for the ',' that comes after "number":
int endIndex = strValue.IndexOf(',', startIndex);
int length = endIndex - startIndex;
// Note, we could potentially get an ArguementOutOfRangeException here.
// You'll want to handle cases where startPosition < 0 or length < 0.
string justTheNumber = strValue.Substring(startIndex, length);
Note: This solution does not handle if "number": is the last entry in the list inside your string, but it should handle every other placement in it.
If your strings get more complex, you could try using Regular Expressions to perform your searches.
Parsing JSON spring in that way is very bad practice as everything is hardcoded. Have you though of using 3rd party library for parsing JSON strings, like Newtonsoft JSON.
I guess you needed to use IndexOf(",") istead of IndexOf("data")

Convert String to Integer [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
how can I convert String to Int ?
Hi,
I have the following problem converting string to an integer:
string str = line.Substring(0,1);
//This picks an integer at offset 0 from string 'line'
So now string str contains a single integer in it. I am doing the following:
int i = Convert.ToInt32(str);
i should be printing an integer if I write the following statement right?
Console.WriteLine(i);
It compiles without any error but gives the following error on runtime:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
Any help please?
Rather than using Convert.ToInt32(string) you should consider using Int32.TryParse(string, out int) instead. The TryParse methods are there to help deal with user-provided input in a safer manner. The most likely cause of your error is that the substring you are returning has an invalid string representation of an integer value.
string str = line.Substring(0,1);
int i = -1;
if (Int32.TryParse(str, out i))
{
Console.WriteLine(i);
}
FormatException
value does not consist of an optional
sign followed by a sequence of digits
(0 through 9).
The exception that is thrown when the
format of an argument does not meet
the parameter specifications of the
invoked method.
You can use Int32.TryParse if you don't want to generate an exception like this.
Int32.TryParse: Converts the string representation of
a number to its 32-bit signed integer
equivalent. A return value indicates
whether the operation succeeded.
It's entirely possible there is some whitespace in there. Try running something akin to trim() (I'm not sure what language you're in) that will strip the white space. Also, try printing out the string to make sure you actually have the right part of it. We've all done that :)
It's likely that your input is not a valid format. Try this instead. If the number is not valid, it should output an error.
Keep in mind that the string should consist of an optional sign followed by a number.
string line = "23"; // or whatever.
string str = line.Substring(0,1);
int i = 0;
if (Int32.TryParse(str, out i)) {
Console.WriteLine(i);
} else {
Console.WriteLine ("Error converting '" + line + "', '" + str + "'.");
}
One thing you may be seeing is the user entering "-1" for example. If you do the substring(0,1) on that, you'll only get "-" which isn't really valid.
Are you sure that the value returned in str is an int, set a debug point if your using visual studio. Ive got a feeling your problem maybe that your not actually returning an integer. Try:
line.Trim().Substring(0,1);
This will remove any whitespace.

Categories

Resources