Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #2876 Allow the contents of a JsonToken.Raw token to be returne… #2877

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8213,5 +8213,18 @@ private static int GetDepth(JToken o)

return depth;
}

[Test]
public void RoundTripDecimalContainerWithConverter()
{
DecimalContainer container = new DecimalContainer
{
Value = 200.100M
};

JToken wrapped = JToken.FromObject(container);
DecimalContainer newContainer = wrapped.ToObject<DecimalContainer>();
Assert.AreEqual(container.Value, newContainer.Value);
}
}
}
8 changes: 8 additions & 0 deletions Src/Newtonsoft.Json.Tests/TestObjects/DecimalContainer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Newtonsoft.Json.Tests.TestObjects
{
[JsonConverter(typeof(DecimalContainerConverter))]
public class DecimalContainer
{
public decimal Value { get; set; }
}
}
33 changes: 33 additions & 0 deletions Src/Newtonsoft.Json.Tests/TestObjects/DecimalContainerConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#nullable enable
using System;

namespace Newtonsoft.Json.Tests.TestObjects
{
public class DecimalContainerConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => true;

public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
reader.Read();
var value = reader.ReadAsString();
var result = new DecimalContainer
{
Value = decimal.Parse(value ?? "0"),
};

reader.Read();
return result;
}

public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
var x = (DecimalContainer)value!;
writer.WriteStartObject();
writer.WritePropertyName("D");
writer.WriteRawValue(x.Value.ToString());
writer.WriteEndObject();
}
}
}
#nullable restore
1 change: 1 addition & 0 deletions Src/Newtonsoft.Json/JsonReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,7 @@ private JsonContainerType Peek()
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Raw:
case JsonToken.String:
return (string?)Value;
}
Expand Down