You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
[JsonConverter(typeof(DecimalLikeConverter))]publicclassDecimalLikeThing{publicdecimalD{get;set;}}publicclassDecimalLikeConverter:JsonConverter{publicoverrideboolCanConvert(TypeobjectType)=>true;publicoverrideobject?ReadJson(JsonReaderreader,TypeobjectType,object?existingValue,JsonSerializerserializer){
reader.Read();varvalue= reader.ReadAsString();varresult=new DecimalLikeThing
{D=decimal.Parse(value??"0"),};
reader.Read();returnresult;}publicoverridevoidWriteJson(JsonWriterwriter,object?value,JsonSerializerserializer){varx=(DecimalLikeThing)value!;
writer.WriteStartObject();
writer.WritePropertyName("D");
writer.WriteRawValue(x.D.ToString());
writer.WriteEndObject();}}publicvoid Run(){
var x =new DecimalLikeThing
{
D =100.300M,};varres= JToken.FromObject(x);
res.ToObject<DecimalLikeThing>();//<-- This throws the exception noted belowvartext= res.ToString(Formatting.None);vartext= res.ToString(Formatting.None);varf= JsonConvert.DeserializeObject(text,typeof(DecimalLikeThing));// <-- This succeeds because the JToken doesn't contain a token noted to by of type Raw}
Source/destination JSON
{"D": 100.300}
Expected behavior
The ReadAsString() call in the JsonConverter above should have returned the text captured in the Raw type token
Actual behavior
Newtonsoft.Json.JsonReaderException: 'Error reading string. Unexpected token: Raw. Path 'D'.'
at Newtonsoft.Json.JsonReader.ReadAsString() in /_/Src/Newtonsoft.Json/JsonReader.cs:line 507
The text was updated successfully, but these errors were encountered:
It's debatable whether this is a bug requiring a fix or whether this is intentional behavior, and since i am not the author nor a maintainer of Newtonsoft.Json i leave it to them to evaluate this situation.
However, as a side note and unrelated to the issue your report is about, please note that doing writer.WriteRawValue(x.D.ToString()); in your WriteJson method is wrong, as it can lead to invalid json. Transforming the decimal to a string using the parameterless ToString() method uses the current culture. If the current culture uses a decimal comma, writing x.D.ToString() as raw value will screw up the resulting json.
Source/destination types and Repro Steps
Source/destination JSON
Expected behavior
The
ReadAsString()
call in the JsonConverter above should have returned the text captured in the Raw type tokenActual behavior
Newtonsoft.Json.JsonReaderException: 'Error reading string. Unexpected token: Raw. Path 'D'.'
at Newtonsoft.Json.JsonReader.ReadAsString() in /_/Src/Newtonsoft.Json/JsonReader.cs:line 507
The text was updated successfully, but these errors were encountered: