Skip to content

Utf8JsonWriter WriteXValue methods assume an array is being written to #11360

Closed
@Reprevise

Description

@Reprevise

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

dotnet-policy-service commented on May 27, 2025

@dotnet-policy-service
Contributor

Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis
See info in area-owners.md if you want to be subscribed.

eiriktsarpalis

eiriktsarpalis commented on May 28, 2025

@eiriktsarpalis
Member

Thanks, this is clearly incorrect and should be fixed. The methods can be used to write a value in any context.

added this to the Backlog milestone on May 28, 2025
Reprevise

Reprevise commented on May 28, 2025

@Reprevise
Author

What about the call to SetFlagToAddListSeparatorBeforeNextItem() inside WriteStringValue(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

eiriktsarpalis commented on May 29, 2025

@eiriktsarpalis
Member

That's just implementation detail, setting a flag that is invariant when writing in non-array contexts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

    Participants

    @eiriktsarpalis@Reprevise

    Issue actions

      Utf8JsonWriter WriteXValue methods assume an array is being written to · Issue #11360 · dotnet/dotnet-api-docs