[Fork] https://stackoverflow.com/questions/76263968/c-sharp-parse-byte-to-json-without-converting-to-base64-string

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Text.Json.Nodes;

using NUnit.Framework; // Throws NUnit.Framework.AssertionException

#nullable enable

//https://stackoverflow.com/questions/76263968/c-sharp-parse-byte-to-json-without-converting-to-base64-string

	public class ByteArrayConverter : JsonConverter<byte []>
	{
		public override void Write(Utf8JsonWriter writer, byte [] value, JsonSerializerOptions options) =>
			JsonSerializer.Serialize(writer, value.AsEnumerable());
		
        public override byte []? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
			reader.TokenType switch
			{
				JsonTokenType.String => reader.GetBytesFromBase64(),
				JsonTokenType.StartArray => JsonSerializer.Deserialize<List<byte>>(ref reader)!.ToArray(),
				JsonTokenType.Null => null,
				_ => throw new JsonException(),
			};
	}

	public class MyModel
	{
		public int Id { get; set; }
		public byte [] Data { get; set; }
	}

    class TestClass
    {
        public static void Test()
        {
			
			MyModel myObject = new MyModel
			{
				Id = 1,                
				Data = new byte[] { 0x01, 0x02, 0x03 }
			};
			var options = new JsonSerializerOptions { Converters = { new ByteArrayConverter() } };
	        string json = JsonSerializer.Serialize(myObject, options);
			
			Console.WriteLine(json);
			
			var model2 = JsonSerializer.Deserialize<MyModel>(json, options);
			Assert.That(myObject.Data.SequenceEqual(model2!.Data));
			
			var base64json = JsonSerializer.Serialize(myObject);
			Console.Write("\nTesting deserialization of {0} also... ", base64json);
			var model3 = JsonSerializer.Deserialize<MyModel>(base64json, options);
			Assert.That(myObject.Data.SequenceEqual(model3!.Data));
			Console.WriteLine(" passed.");
			
		}	
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
			Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}
;