Skip to content
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ For a type to work with RoundTripStringJsonConverter, it must meet these require

A type that names its own converter with a type-level `[JsonConverter(typeof(...))]` attribute is left to that converter, even when the factory is registered in `JsonSerializerOptions.Converters` and the type has a supported conversion method. Registering the factory never changes the wire format of such a type. The exception is an attribute that names the factory itself, `[JsonConverter(typeof(RoundTripStringJsonConverterFactory))]`, which opts that one type in without registering the factory globally; such a type is converted with or without the factory in `JsonSerializerOptions.Converters`, including as a dictionary key.

A type that has a conversion method but doesn't override `ToString()`, itself or through a base class, is left to System.Text.Json's default object serialization. Writing it through `ToString()` would only record its type name. An abstract base class or an interface with a conversion method is still converted, because the value written is always a derived or implementing type whose own `ToString()` override supplies the string.
A type that has a conversion method but doesn't override `ToString()`, itself or through a base class, is left to System.Text.Json's default object serialization. Writing it through `ToString()` would only record its type name. The same goes for a `record` or `record struct` whose only `ToString()` is the one the compiler generates, which writes the debug form `Email { Value = a@b.c }`. Declare `ToString()` on the record to have it written as a string. An abstract base class or an interface with a conversion method is still converted, because the value written is always a derived or implementing type whose own `ToString()` override supplies the string.

#### Valid Method Signatures

Expand Down
93 changes: 93 additions & 0 deletions RoundTripStringJsonConverter.Test/ToStringOverrideTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,42 @@ public sealed class InheritsToString(string value) : StringBase(value)
public static InheritsToString FromString(string value) => new(value);
}

public sealed record Email(string Value)
{
public static Email Create(string value) => new(value);
}

public readonly record struct Pt(int X, int Y)
{
public static Pt Parse(string value)
{
string[] parts = (value ?? throw new System.ArgumentNullException(nameof(value))).Split(',');
return new(int.Parse(parts[0], System.Globalization.CultureInfo.InvariantCulture), int.Parse(parts[1], System.Globalization.CultureInfo.InvariantCulture));
}
}

public sealed record Sku(string Value)
{
public static Sku Parse(string value) => new(value);

public override string ToString() => Value;
}

public abstract record SealedStringRecord(string Value)
{
public sealed override string ToString() => Value;
}

public sealed record Tag(string Value) : SealedStringRecord(Value)
{
public static Tag FromString(string value) => new(value);
}

public sealed class EmailHolder
{
public Email? To { get; set; }
}

public sealed class WidgetHolder
{
public FactoryWidget? W { get; set; }
Expand Down Expand Up @@ -115,4 +151,61 @@ public void RoundTrip_TypeInheritingToStringOverride_IsWrittenAsString()
Assert.AreEqual("\"abc\"", json);
Assert.AreEqual("abc", back?.Value);
}

[TestMethod]
public void CanConvert_RecordWithFactoryButOnlyCompilerGeneratedToString_ReturnsFalse()
{
RoundTripStringJsonConverterFactory factory = new();
Assert.IsFalse(factory.CanConvert(typeof(Email)));
}

[TestMethod]
public void CanConvert_RecordStructWithParseButOnlyCompilerGeneratedToString_ReturnsFalse()
{
RoundTripStringJsonConverterFactory factory = new();
Assert.IsFalse(factory.CanConvert(typeof(Pt)));
}

[TestMethod]
public void CanConvert_RecordDeclaringItsOwnToString_ReturnsTrue()
{
RoundTripStringJsonConverterFactory factory = new();
Assert.IsTrue(factory.CanConvert(typeof(Sku)));
}

[TestMethod]
public void CanConvert_RecordInheritingSealedToString_ReturnsTrue()
{
RoundTripStringJsonConverterFactory factory = new();
Assert.IsTrue(factory.CanConvert(typeof(Tag)));
}

[TestMethod]
public void RoundTrip_RecordWithOnlyCompilerGeneratedToString_KeepsItsData()
{
string json = JsonSerializer.Serialize(new EmailHolder { To = Email.Create("a@b.c") }, Options);
EmailHolder? back = JsonSerializer.Deserialize<EmailHolder>(json, Options);

Assert.AreEqual("{\"To\":{\"Value\":\"a@b.c\"}}", json);
Assert.AreEqual(Email.Create("a@b.c"), back?.To);
}

[TestMethod]
public void RoundTrip_RecordStructWithOnlyCompilerGeneratedToString_KeepsItsData()
{
string json = JsonSerializer.Serialize(new Pt(1, 2), Options);
Pt back = JsonSerializer.Deserialize<Pt>(json, Options);

Assert.AreEqual("{\"X\":1,\"Y\":2}", json);
Assert.AreEqual(new Pt(1, 2), back);
}

[TestMethod]
public void RoundTrip_RecordDeclaringItsOwnToString_IsWrittenAsString()
{
string json = JsonSerializer.Serialize(Sku.Parse("X-1"), Options);

Assert.AreEqual("\"X-1\"", json);
Assert.AreEqual(Sku.Parse("X-1"), JsonSerializer.Deserialize<Sku>(json, Options));
}
}
10 changes: 9 additions & 1 deletion RoundTripStringJsonConverter/RoundTripStringJsonConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
Expand Down Expand Up @@ -142,7 +143,7 @@
/// <param name="type">The type to convert to.</param>
/// <param name="conversionMethod">The method chosen by <see cref="FindStringConversionMethod"/>.</param>
/// <returns>The single-string overload, or null if there is nothing to fall back to.</returns>
private static MethodInfo? FindCurrentCultureFallbackMethod(Type type, MethodInfo? conversionMethod)

Check warning on line 146 in RoundTripStringJsonConverter/RoundTripStringJsonConverter.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Move this method inside 'RoundTripStringJsonConverter'.
{
if (conversionMethod is null || !TakesFormatProvider(conversionMethod) || !typeof(IFormattable).IsAssignableFrom(type))
{
Expand Down Expand Up @@ -237,7 +238,7 @@
/// <param name="method">The conversion method.</param>
/// <param name="value">The string to convert.</param>
/// <returns>The arguments to invoke the method with.</returns>
private static object?[] BuildArguments(MethodInfo method, string value)

Check warning on line 241 in RoundTripStringJsonConverter/RoundTripStringJsonConverter.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Move this method inside 'RoundTripStringJsonConverter'.
{
ParameterInfo[] parameters = method.GetParameters();
object?[] arguments = new object?[parameters.Length];
Expand Down Expand Up @@ -282,7 +283,7 @@
/// <returns>True if the type can be converted; otherwise, false.</returns>
public override bool CanConvert(Type typeToConvert)
{
Ensure.NotNull(typeToConvert, nameof(typeToConvert));

Check warning on line 286 in RoundTripStringJsonConverter/RoundTripStringJsonConverter.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Remove this argument from the method call; it hides the caller information.

// Don't convert built-in types
if (IsBuiltInType(typeToConvert))
Expand Down Expand Up @@ -322,6 +323,12 @@
/// interface passes: no instance of it exists, so the value written is always a derived or implementing
/// type, which supplies <c>ToString()</c> itself.
/// </summary>
/// <remarks>
/// The <c>ToString()</c> the compiler synthesizes for a <c>record</c> or <c>record struct</c> does not
/// count: it prints the debug form <c>TypeName { Prop = value }</c>, which no conversion method reads
/// back. A record that declares its own <c>ToString()</c>, or inherits a sealed one, still counts,
/// because the compiler then synthesizes nothing.
/// </remarks>
/// <param name="type">The type to check.</param>
/// <returns>True if <c>ToString()</c> is overridden, or the type is abstract or an interface; otherwise, false.</returns>
private static bool OverridesToString(Type type)
Expand All @@ -335,7 +342,8 @@
MethodInfo? toString = type.GetMethod(nameof(ToString), BindingFlags.Public | BindingFlags.Instance, binder: null, Type.EmptyTypes, modifiers: null);
return toString is not null
&& toString.DeclaringType != typeof(object)
&& toString.DeclaringType != typeof(ValueType);
&& toString.DeclaringType != typeof(ValueType)
&& !toString.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false);
}

/// <summary>
Expand All @@ -346,8 +354,8 @@
/// <returns>A JSON converter for the specified type.</returns>
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
Ensure.NotNull(typeToConvert, nameof(typeToConvert));

Check warning on line 357 in RoundTripStringJsonConverter/RoundTripStringJsonConverter.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Remove this argument from the method call; it hides the caller information.
Ensure.NotNull(options, nameof(options));

Check warning on line 358 in RoundTripStringJsonConverter/RoundTripStringJsonConverter.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Remove this argument from the method call; it hides the caller information.
Type converterType = typeof(RoundTripStringJsonConverter<>).MakeGenericType(typeToConvert);
return (JsonConverter)Activator.CreateInstance(converterType, BindingFlags.Instance | BindingFlags.Public, binder: null, args: null, culture: null)!;
}
Expand Down Expand Up @@ -463,7 +471,7 @@
/// <returns>The converted value.</returns>
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Ensure.NotNull(typeToConvert, nameof(typeToConvert));

Check warning on line 474 in RoundTripStringJsonConverter/RoundTripStringJsonConverter.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Remove this argument from the method call; it hides the caller information.

if (reader.TokenType == JsonTokenType.Null)
{
Expand All @@ -476,7 +484,7 @@
}

string? stringValue = reader.GetString();
Ensure.NotNull(stringValue, nameof(stringValue));

Check warning on line 487 in RoundTripStringJsonConverter/RoundTripStringJsonConverter.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Remove this argument from the method call; it hides the caller information.

return InvokeStringConversionMethod(stringValue);
}
Expand All @@ -491,10 +499,10 @@
/// <returns>The converted value.</returns>
public override T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Ensure.NotNull(typeToConvert, nameof(typeToConvert));

Check warning on line 502 in RoundTripStringJsonConverter/RoundTripStringJsonConverter.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Remove this argument from the method call; it hides the caller information.

string? stringValue = reader.GetString();
Ensure.NotNull(stringValue, nameof(stringValue));

Check warning on line 505 in RoundTripStringJsonConverter/RoundTripStringJsonConverter.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Remove this argument from the method call; it hides the caller information.

return InvokeStringConversionMethod(stringValue);
}
Expand Down Expand Up @@ -593,7 +601,7 @@
/// <param name="options">Options to control the behavior during serialization and deserialization.</param>
public override void WriteAsPropertyName(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
Ensure.NotNull(writer, nameof(writer));

Check warning on line 604 in RoundTripStringJsonConverter/RoundTripStringJsonConverter.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Remove this argument from the method call; it hides the caller information.

#pragma warning disable KTSU0004 // Use Ensure.NotNull instead of manual null check
if (value is null)
Expand Down
Loading