Skip to content

Commit

Permalink
Add custom byteArray formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
AMPing committed Mar 19, 2022
1 parent 567640d commit 734730c
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/Utf8Json/Formatters/ByteArrayAsListFormatter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace Utf8Json.Formatters
{
// MEMO: Not recommended. should write/read base64 directly like corefxlab/System.Binary.Base64
// https://github.com/dotnet/runtime/issues/30456
public sealed class ByteArrayAsListFormatter : IJsonFormatter<byte[]>
{
public static readonly IJsonFormatter<byte[]> Default = new ByteArrayAsListFormatter();

public void Serialize(ref JsonWriter writer, byte[] value, IJsonFormatterResolver formatterResolver)
{
if (value == null) { writer.WriteNull(); return; }

new ArrayFormatter<byte>().Serialize(ref writer, value, formatterResolver);
}

public byte[] Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull()) return null;

if (reader.GetCurrentJsonToken() == JsonToken.BeginArray)
{
return new ArrayFormatter<byte>().Deserialize(ref reader, formatterResolver);
}

return ByteArrayFormatter.Default.Deserialize(ref reader, formatterResolver);
}
}
}
25 changes: 25 additions & 0 deletions tests/Utf8Json.Tests/FormatterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -201,5 +201,30 @@ public void UriTest()
var relative = new Uri("/me/", UriKind.Relative);
Convert(relative).ToString().Is("/me/");
}

[Fact]
public void ByteArrayAsListTest()
{
Resolvers.CompositeResolver.RegisterAndSetAsDefault
(
new IJsonFormatter[]
{
Formatters.ByteArrayAsListFormatter.Default,
},

new IJsonFormatterResolver[]
{
Resolvers.StandardResolver.Default,
});

var bytes = new byte[] { 123, 10 };
var c = Convert(bytes);

c[0].Is((byte)123);
c[1].Is((byte)10);

var json = JsonSerializer.ToJsonString(bytes);
json.Is("[123,10]");
}
}
}

0 comments on commit 734730c

Please sign in to comment.