Background and motivation
The JsonEncodedText struct encapsulates both the UTF8 and string representations of the encoded value, however only the UTF8 value is accessible via the EncodedUtf8Bytes property. This makes the type more difficult to use in deserialization scenaria, for instance:
public class MyConverter : JsonConverter<Foo>
{
private readonly JsonEncodedText _preEncodedPropertyName = JsonEncodedText.Encode("propertyName");
public override void Write(Utf8JsonWriter writer, Foo value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WriteString(_propertyName.Utf8EncodedBytes, value.Value);
writer.WriteEndObject();
}
public override Foo Read(ref Utf8JsonReader reader, Type ttc, JsonSerializerOptions options)
{
reader.Read();
reader.Read();
Debug.Assert(reader.TokenType == JsonTokenType.PropertyName);
string propertyName = reader.ReadPropertyName();
if (_preEncodedPropertyName.ToString() == propertyName) // there's no proper way to fetch the UTF-16 variant when serializing
{
/* read the property value */
}
}
}
API Proposal
namespace System.Text.Json;
public struct JsonEncodedValue
{
public ReadOnlySpan<byte> EncodedUtf8Bytes => _utf8Value;
+ public string Value => _value ?? string.Empty;
}
API Usage
From the previous example:
public override Foo Read(ref Utf8JsonReader reader, Type ttc, JsonSerializerOptions options)
{
reader.Read();
reader.Read();
Debug.Assert(reader.TokenType == JsonTokenType.PropertyName);
string propertyName = reader.ReadPropertyName();
if (_preEncodedPropertyName.Value == propertyName) // there's no proper way to fetch the UTF-16 variant when serializing
{
/* read the property value */
}
}
Alternative Designs
We might expose the property as ReadOnlySpan<char>, but there's currently no reason why we would want to do this; the current implementation will always create a string for the UTF-16 representation.
Risks
No response
Background and motivation
The
JsonEncodedTextstruct encapsulates both the UTF8 and string representations of the encoded value, however only theUTF8value is accessible via theEncodedUtf8Bytesproperty. This makes the type more difficult to use in deserialization scenaria, for instance:API Proposal
namespace System.Text.Json; public struct JsonEncodedValue { public ReadOnlySpan<byte> EncodedUtf8Bytes => _utf8Value; + public string Value => _value ?? string.Empty; }API Usage
From the previous example:
Alternative Designs
We might expose the property as
ReadOnlySpan<char>, but there's currently no reason why we would want to do this; the current implementation will always create a string for the UTF-16 representation.Risks
No response