简体   繁体   English

将 Newtonsoft JSON 序列化为字节数组

[英]Serialize Newtonsoft JSON to byte array

What I am aiming to do is send JSON containing a header object and a compressed data in a field that is byte array.我的目标是在字节数组字段中发送包含标头对象和压缩数据的 JSON。

[JsonObject(MemberSerialization.OptOut)]
public class Message
{
    public Message()
    {
        Header = new Header();
    }

    public Header Header { get; set; }


    public byte[] Data { get; set; }
}

Byte array is gzip compressed JSON object, but this is not that relevant.字节数组是 gzip 压缩的 JSON 对象,但这无关紧要。 Issue I am having is that if I serialize the JSON it gets converted into string and then back to bytes.我遇到的问题是,如果我序列化 JSON,它会转换为字符串,然后再转换回字节。 Issue is, the message size increases quite a bit , since serializing the byte array converts it to string representation.问题是,消息大小增加了很多,因为序列化字节数组会将其转换为字符串表示。

I am constrained by maximum message size and I have spiting of compressed data in place, but when I get to send the JSON containing compressed data in Byte array and Uncompressed header, serializing JSON object puts me way over the message size limit.我受到最大消息大小的限制,并且我已经准备好压缩数据,但是当我要发送包含字节数组和未压缩标头中的压缩数据的 JSON 时,序列化 JSON 对象使我超出了消息大小限制。

Is there any reliable way of converting JSON object to byte array straight away.是否有任何可靠的方法可以立即将 JSON 对象转换为字节数组。

           var stringMessage = JsonConvert.SerializeObject(message,Formatting.None);
            var bytes = Encoding.UTF8.GetBytes(stringMessage);

            var stringMessage2 = JsonConvert.SerializeObject(message.TransportHeader, Formatting.None);
            var bytes2 = Encoding.UTF8.GetBytes(stringMessage2);

            Message eventMessage = new Message(bytes);
            var bytes3= Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message.Transportdata));

Compressed data size =243905压缩数据大小 =243905

Full JSON in Bytes after serialization = 325313序列化后以字节为单位的完整 JSON = 325313

Just header in bytes size =90仅以字节为单位的标头大小 = 90

Just Compressed data serialized and converted back to bytes = 325210, (size increases when data gets serialized by JsonConvert.SerializeObject and string representation is produced)只是将压缩数据序列化并转换回字节 = 325210,(当数据被 JsonConvert.SerializeObject 序列化并产生字符串表示时,大小会增加)

It clearly goes up quite a bit and its caused by byte array.它显然上升了很多,并且是由字节数组引起的。

I found a way to do what I wanted, its not precisely JSON, buts is BSON or also known as Binary JSON.我找到了一种方法来做我想做的事,它不完全是 JSON,而是 BSON 或也称为二进制 JSON。 Well since finding the solution was a pure luck, I am not sure how well known is BSON.好吧,既然找到解决方案纯属运气,我不确定 BSON 的知名度如何。

Anyway Newtonsoft supports it via Newtonsoft.Json.Bson nuget package at https://www.nuget.org/packages/Newtonsoft.Json.Bson/1.0.1无论如何,Newtonsoft 通过位于https://www.nuget.org/packages/Newtonsoft.Json.Bson/1.0.1 的Newtonsoft.Json.Bson nuget 包支持它

Some code for serialization/deserialization一些用于序列化/反序列化的代码

            foreach (var message in transportMessageList)
        {
            MemoryStream ms = new MemoryStream();
            using (BsonDataWriter writer = new BsonDataWriter(ms))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(writer, message);
            }

            var bsonByteArray = ms.ToArray();
            Assert.True(bsonByteArray.Length!=0);
            bsonList.Add(bsonByteArray);
        }

        var deserializdTransmortMessageList = new List<TransportMessage>();
        foreach (var byteArray in bsonList)
        {
            TransportMessage message;
            MemoryStream ms = new MemoryStream(byteArray);
            using (BsonDataReader reader = new BsonDataReader(ms))
            {
                JsonSerializer serializer = new JsonSerializer();
                message = serializer.Deserialize<TransportMessage>(reader);
            }
            Assert.True(message.Transportdata.Length!=0);
            deserializdTransmortMessageList.Add(message);
        }

You can use same classes/objects you use for JSON, serializing compressed array of bytes no longer cause an increase in size.您可以使用与 JSON 相同的类/对象,序列化压缩的字节数组不再导致大小增加。

Please note that BSON documentation at Newtonsoft website is out dated and lists only deprecated api calls at this moment.请注意,Newtonsoft 网站上的 BSON 文档已过时,目前仅列出已弃用的 api 调用。 My code uses proper non deprecated API calls.我的代码使用正确的非弃用 API 调用。

JSON is a character based format so there is necessarily character data involved. JSON 是一种基于字符的格式,因此必然涉及字符数据。 I suspect you used UTF16 encoding which makes each char into two bytes.我怀疑你使用了 UTF16 编码,它使每个字符变成两个字节。 If you use UTF8 you will not experience any meaningful size overhead.如果您使用UTF8您将不会遇到任何有意义的大小开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM