Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonConvert.DeserializeObject<string> throws an exception on a simple string [closed]

Tags:

json

c#

json.net

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.

like image 577
Spellchamp Avatar asked May 06 '26 15:05

Spellchamp


1 Answers

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.

like image 163
Spellchamp Avatar answered May 08 '26 05:05

Spellchamp