相关文章推荐
老实的稀饭  ·  FFmpeg Javacv ...·  9 月前    · 
霸气的花卷  ·  SVN - Change working ...·  1 年前    · 
销魂的水桶  ·  在Visual - Microsoft ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I use JSON.net to serialize some objects between C# and JavaScript. The JSON data is transfered via WebSocket between the .NET and browser application.

In the data structure there are some byte[] fields, I want these fields as an Array in JavaScript also.

How can I serialize a C# byte[] to a simple JSON Array like [ 0 , 1 , 254, 255 ] instead of a base64 string?

JSON.NET is selecting the BinaryConverter to read and write an array of bytes. You can see in the source that it uses the WriteValue operation on the JsonWriter class with the array of bytes which causes them to be written to as Base-64.

To modify this, you can write your own converter which reads and writes an array in the format you expect:

public class ByteArrayConverter : JsonConverter
    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
        if (value == null)
            writer.WriteNull();
            return;
        byte[] data = (byte[])value;
        // Compose an array.
        writer.WriteStartArray();
        for (var i = 0; i < data.Length; i++)
            writer.WriteValue(data[i]);
        writer.WriteEndArray();
    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
        if (reader.TokenType == JsonToken.StartArray)
            var byteList = new List<byte>();
            while (reader.Read())
                switch (reader.TokenType)
                    case JsonToken.Integer:
                        byteList.Add(Convert.ToByte(reader.Value));
                        break;
                    case JsonToken.EndArray:
                        return byteList.ToArray();
                    case JsonToken.Comment:
                        // skip
                        break;
                    default:
                        throw new Exception(
                        string.Format(
                            "Unexpected token when reading bytes: {0}",
                            reader.TokenType));
            throw new Exception("Unexpected end when reading bytes.");
            throw new Exception(
                string.Format(
                    "Unexpected token parsing binary. "
                    + "Expected StartArray, got {0}.",
                    reader.TokenType));
    public override bool CanConvert(Type objectType)
        return objectType == typeof(byte[]);

You would use this by applying the JsonConverterAttribute to the member:

[JsonConverter(typeof(ByteArrayConverter))]
public byte[] Data { get; set; }
                Bonus points for providing the actual ByteArrayConverter class! However, there is a small error. Because you're already using a JsonWriter, there is no need to add the comma's manually, so you can just remove this part:  if(i != data.Length) {     writer.WriteRaw(","); } Otherwise your array will look like this: [12,,54,,32,,8]
– Bram Vandenbussche
                May 12, 2015 at 9:58

Simplest way I can think of is to convert the byte array into an integer array, like:

var intArray = byteArray.Select(b => (int)b).ToArray();

This wouldn't require any special handling of the JSON library, or any custom serialization or anything like that.

EDIT: This would mean having to customize your data object to handle the different type. Maybe:

public class CustomFoo : Foo
    // SomeBytesHere is a byte[] in the base class
    public new int[] SomeBytesHere { get;set; }

So maybe it's not the simplest - depending on how much stuff you have to serialize

I love the 'int Array' solution. Work's great and simple to implement. Many thank's for that hint. – Marcus Mar 6, 2013 at 6:51 Bravo. A byte fits into an int, and the whole int[] is an array of bytes. WCF with a JSON binding on the other end can take a JSON serialized DTO with a byte[] property and safely deserialize it without any custom formatters or base64 decode/Stream writing. The size of the serialized JSON is pretty magnificent, but it works! – Chris Kissinger Mar 14, 2014 at 20:28 It will use 8 times the memory of the byte array though, so not always a viable solution. – FINDarkside Feb 15, 2018 at 16:25

Ref my answer, JSON.net can customze serialization in setting for all instead of attribute in property.

You can easily change it from base64 to number array, just write a square bracketed csv raw value.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.