Utf8Json続きでTextを取得したい場合に、パフォーマンスのためにstringに変換せずにutf8-byte[]で取得したい場合があるかと思います。
私は、byte[]の値に、属性[JsonFormatter(typeof(Utf8BytesFormatter))]を付与する方法と、byte[]をラップしたstructで受け取る方法を使い分けしています。
以下にサンプルコードを載せておきます。
[JsonFormatter(typeof(Utf8StructFormatter))]
public struct Utf8Struct
{
public byte[] Value;
public Utf8Struct(byte[] value)
{
this.Value = value;
}
}
public sealed class Utf8StructFormatter : IJsonFormatter<Utf8Struct>
{
public static readonly Utf8StructFormatter Default = new Utf8StructFormatter();
public void Serialize(ref JsonWriter writer, Utf8Struct value, IJsonFormatterResolver formatterResolver)
{
writer.WriteUtf8Bytes(value.Value);
}
public Utf8Struct Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var result = new Utf8Struct();
result.Value = reader.ReadUtf8Bytes();
return result;
}
}
public sealed class Utf8BytesFormatter : IJsonFormatter<byte[]>
{
public static readonly Utf8BytesFormatter Default = new Utf8BytesFormatter();
public void Serialize(ref JsonWriter writer, byte[] value, IJsonFormatterResolver formatterResolver)
{
writer.WriteUtf8Bytes(value);
}
public byte[] Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
return reader.ReadUtf8Bytes();
}
}
public static class JsonWriterExtensions
{
public static void WriteUtf8Bytes(ref this JsonWriter writer, byte[] value)
{
writer.EnsureCapacity(value.Length + 2);
writer.WriteRawUnsafe((byte)'\"');
for (int i = 0; i < value.Length; i++)
{
writer.WriteRawUnsafe(value[i]);
}
writer.WriteRawUnsafe((byte)'\"');
}
}
public static class JsonReaderExtensions
{
public static byte[] ReadUtf8Bytes(ref this JsonReader reader)
{
reader.SkipWhiteSpace();
return reader.ReadStringSegmentUnsafe().ToArray();
}
}