Why does the following code
string x = "Some text.";
JsonConvert.DeserializeObject<string>(x);
throw this exception:
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: S. Path '', line 1, position 1. at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType) at Newtonsoft.Json.JsonTextReader.ReadAsString() at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings) at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value) at TestStuff2.Program.Main(String[] args)
As far as I know, strings are valid JSON, and JSONLint agrees with me.
Could this be an encoding issue?
Note that this works if I change the value of x to a number. For example:
string x = "100";
JsonConvert.DeserializeObject<string>(x);
Works just fine.
Figured it. Turns out that it was to do with quotation marks:
string x = "\"Some text.\"";
JsonConvert.DeserializeObject<string>(x);
Works fine, since the Deserializer expects strings to start with quotation marks. But the string I was passing into the Deserializer didn't start with any.
So I was originally trying to deserialize:
Some text.
Which is not valid JSON. So instead I want to deserialize:
"Some text."
Which is valid JSON.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With