Context
The line JsonConvert.SerializeObject(DateTime.Now) gives the following result:
"2018-05-25T07:59:27.2175427+02:00"
However when I try to deserialize this JSON string to a DateTime with the line: JsonConvert.DeserializeObject<DateTime>("2018-05-25T07:59:27.2175427+02:00")
it gives an Newtonsoft.Json.JsonReaderException with the following message:
Unexpected character encountered while parsing value: 2. Path '', line 1, position 1.
What else I've tried so far
"2018-05-25T07:59:27"
causes the very same exception
Question
Having the datetime string in JSON serialized format, I would like to have a DateTime variable and the correct value in it. How can I accomplish this task?
As shown in the JSON standard, a JSON string literal must be quoted:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
Thus, to be valid JSON, your c# string literal must include the surrounding double quotes, like so:
var dateTime = JsonConvert.DeserializeObject<DateTime>("\"2018-05-25T07:59:27.2175427+02:00\"");
It's easy to confuse the outermost quotes, which are part of the c# language and delimit the string in your c# code but are not included in the string itself, with the inner quotes, which are part of the string literal itself.
Sample fiddle here.
The problem is that JsonConvert.DeserializeObject looks like it wants a JSON object rather than just any JSON value. (It's a shame that SerializeObject doesn't always produce an object, but...)
You can parse it like this:
DateTime dt = new JValue("2018-05-25T07:59:27.2175427+02:00").ToObject<DateTime>();
Or (equivalently? I'm not entirely sure):
DateTime dt = (DateTime) new JValue("2018-05-25T07:59:27.2175427+02:00");
There may be a better way of doing so, but that at least works.
Related
I have to map this string by specific format into a property of my dataModel, so I use string.Format() to handle it, but I faced a Run time error that says:
Input string was not in a correct format!!!
how could write it in the correct format?
Value = string.Format("guid{({0})}title{({1})}parameterName{({2})}", retirementItem.Guid, retirementItem.Title, retirementItem.ParameterName)
Use the $ - string interpolation syntax. A more readable and convenient syntax to create formatted strings.
If you dont need curly brackets in your string:
Value = $"guid({retirementItem.Guid})title({retirementItem.Title})parameterName({retirementItem.ParameterName})";
If you need them:
Value = $"guid{{({retirementItem.Guid})}}title{{({retirementItem.Title})}}parameterName{{({retirementItem.ParameterName})}}";
The char { and } are keywords in string.Format.
so you have to escape them using {{ and }} like:
Console.WriteLine(string.Format("guid{{({0})}}title{{({1})}}parameterName{{({2})}}", Guid.NewGuid(), "title", "name"));
Context
The line JsonConvert.SerializeObject(DateTime.Now) gives the following result:
"2018-05-25T07:59:27.2175427+02:00"
However when I try to deserialize this JSON string to a DateTime with the line: JsonConvert.DeserializeObject<DateTime>("2018-05-25T07:59:27.2175427+02:00")
it gives an Newtonsoft.Json.JsonReaderException with the following message:
Unexpected character encountered while parsing value: 2. Path '', line 1, position 1.
What else I've tried so far
"2018-05-25T07:59:27"
causes the very same exception
Question
Having the datetime string in JSON serialized format, I would like to have a DateTime variable and the correct value in it. How can I accomplish this task?
As shown in the JSON standard, a JSON string literal must be quoted:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
Thus, to be valid JSON, your c# string literal must include the surrounding double quotes, like so:
var dateTime = JsonConvert.DeserializeObject<DateTime>("\"2018-05-25T07:59:27.2175427+02:00\"");
It's easy to confuse the outermost quotes, which are part of the c# language and delimit the string in your c# code but are not included in the string itself, with the inner quotes, which are part of the string literal itself.
Sample fiddle here.
The problem is that JsonConvert.DeserializeObject looks like it wants a JSON object rather than just any JSON value. (It's a shame that SerializeObject doesn't always produce an object, but...)
You can parse it like this:
DateTime dt = new JValue("2018-05-25T07:59:27.2175427+02:00").ToObject<DateTime>();
Or (equivalently? I'm not entirely sure):
DateTime dt = (DateTime) new JValue("2018-05-25T07:59:27.2175427+02:00");
There may be a better way of doing so, but that at least works.
I got some trouble with a problem when use Newtonsoft json.net to deserialize json string to dictionary. It 's a case of my json string have some special character.
string jsonString = "{\"name\":\"Jones Smith\",\"age\":\"20\",\"description\":\"The one live with \"ALIGATOR\"\"}";
Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
I try to find a solution in the use of json.net but i not found. So the FINAL plan is remove that "characters". So, what is the best solution for this case?
I think you can't do very much in your situation besides changing the format at the origin. The problem with your input is that there are " characters escaped the same way once in your json directly and once in your json values.
Consider the following part: "description":"The one live with "ALIGATOR""
How should a deserializer know which " should be considered part of the value or part of the json format?
I got the answer, like the last comment, that 's not valid JSON, below is valid JSON
{"name":"Jones Smith","age":"20","description":"The one live with \"ALIGATOR\""}
And all i can do is add '\' before special characters if the value of field description is "The one live with "ALIGATOR"" to make a valid JSON and convert to c# like this:
string jsonString = {\"name\":\"Jones Smith\",\"age\":\"20\",\"description\":\"The one live with \\"ALIGATOR\\"\"}
So, the other day I ran into a problem when trying to parse a timestamp which was wrapped in quotes, it looked like this in the file I was reading:
"2018-04-09"
A C# string with this content:
var dt = "\"2018-04-09\""
I wanted to use DateTime.TryParseExact() to convert the string into a .net DateTime object, without stripping the chars from the string (don't ask why, it's not relevant), but finding a working format string turned out to be tricky.
I read the docs. I googled. Searched StackOverflow. No success.
What format would allow me to parse this timestamp to a DateTime object?
So - the solution, handed to me by a colleague:
var format = "\\\"yyyy-MM-dd\\\"";
If I understand this correctly, the format string is expected to contain a \ which is later resolved to escape the " inside ParseExact(). The first \ escapes the second, the third escapes ", leading to the character sequence \" as part of the format string which is then processed somewhere down the line.
The following works:
var dts = "\"2018-04-09\"";
var format = "\\\"yyyy-MM-dd\\\"";
var dt = DateTime.ParseExact(dts, format, null);
I hope this helps someone!
I have been working on a project, and found an interesting problem:
2.ToString("TE"+"000"); // output = TE000
2.ToString("TR"+"000"); // output = TR002
I also have tried with several strings other than "TE" but all have the same correct output.
Out of curiosity, I am wondering how come this could have happened?
Simply based on Microsoft's documentation, Custom Numeric Format Strings, your strings "TE000" and "TR000" are both custom format strings, but clearly they are parsed differently.
2.ToString("TE000") is just a bug in the formatter; it's going down a buggy path because of the unescaped "E". So it's unexpectedly assuming the whole thing is a literal.
2.ToString("TR000") is being interpreted as an implied "TR" literal plus 3 zero-filled digits for an integer value; therefore, you get "TR002".
If you truly want TE and TR verbatim, the expressions 2.ToString("\"TE\"000") and 2.ToString("\"TR\"000") will accomplish that for you by specifying TE and TR as explicit literals, instead of letting the formatter guess if they are valid format specifiers (and getting it wrong).
The ToString needs to PARSE the format string and understand what to do with it.
Let's take a look to the following examples:
2.ToString("TE000"); //output TE000
2.ToString("E000"); //output 2E+000
2.ToString("0TE000); //output 2TE000
2.ToString("T"); //throws exception
2.ToString("TT"); //output TT
This shows that if the ToString parser can understand at least part of the format, it will assume that the rest is just extra characters to print with it. If the format is invalid for the given number (like when you use a DateTime string format on a number), it will throw an exception. If it can not make sense of the format, it will return the format string itself as the result.
You cannot use a numeric format to achieve a custom format, instead use something like this:
int i = 2;
String.Format("TE{0:X3}", i);
See Custom Numeric Format Strings. The E means the exponent part of the scientific notation of the number. Since 2 is 2E000 in exponential notation, that might explain it.