如何将 byte[] 序列化为简单的 JSON 数组而不是 JSON.net 中的 base64? [英] How to serialize byte[] as simple JSON Array and not as base64 in JSON.net?

查看:27
本文介绍了如何将 byte[] 序列化为简单的 JSON 数组而不是 JSON.net 中的 base64?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 JSON.net 在 C# 和 JavaScript 之间序列化一些对象.JSON 数据通过 WebSocket 在 .NET 和浏览器应用程序之间传输.

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.

在数据结构中有一些 byte[] 字段,我希望这些字段也作为 JavaScript 中的 Array .

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

如何将 C# byte[] 序列化为一个简单的 JSON 数组,如 [ 0 , 1 , 254, 255 ] 而不是 base64 字符串?

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

推荐答案

我能想到的最简单的方法就是将字节数组转换成整数数组,比如:

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();

这不需要对 JSON 库进行任何特殊处理,也不需要任何自定义序列化或类似的东西.

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

EDIT:这意味着必须自定义您的数据对象以处理不同的类型.也许:

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

这篇关于如何将 byte[] 序列化为简单的 JSON 数组而不是 JSON.net 中的 base64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆