Closed
Description
The documentation of the WriteXValue
methods assumes you're calling the method to append a value to a JSON array when there other usecases, for example when writing converters (see here).
namespace SystemTextJsonSamples
{
public class DateTimeOffsetJsonConverter : JsonConverter<DateTimeOffset>
{
public override DateTimeOffset Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options) =>
DateTimeOffset.ParseExact(reader.GetString()!,
"MM/dd/yyyy", CultureInfo.InvariantCulture);
public override void Write(
Utf8JsonWriter writer,
DateTimeOffset dateTimeValue,
JsonSerializerOptions options) =>
writer.WriteStringValue(dateTimeValue.ToString( // Call to WriteStringValue
"MM/dd/yyyy", CultureInfo.InvariantCulture));
}
}
Documentation for WriteStringValue
:
Writes a string text value (as a JSON string) as an element of a JSON array.
There's also a method call to SetFlagToAddListSeparatorBeforeNextItem()
inside the WriteStringValue(ReadOnlySpan<char> value)
method.
Activity
dotnet-policy-service commentedon May 27, 2025
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis
See info in area-owners.md if you want to be subscribed.
eiriktsarpalis commentedon May 28, 2025
Thanks, this is clearly incorrect and should be fixed. The methods can be used to write a value in any context.
Reprevise commentedon May 28, 2025
What about the call to
SetFlagToAddListSeparatorBeforeNextItem()
insideWriteStringValue(ReadOnlySpan<char>)
? It seems like this method was intended to be for writing values to arrays. Though this hasn't broken anything (as far as its known).eiriktsarpalis commentedon May 29, 2025
That's just implementation detail, setting a flag that is invariant when writing in non-array contexts.