简体   繁体   中英

Deserialize byte array column in DataTable with JSON.net

I have a project that accepts a SQL server query, passes this query to a web service that executes this query, passes the results back to the client which then returns the DataSet result (as well as a few additional properties). Currently it uses WCF and SOAP for the communication. In order to reduce the total request time I'm trying to move this to Web API and JSON. According to my proof of concept this has cut down the total request time by about 30%, which is significant given the throughput of this service.

My problem is that some of the queries (which I have no control over) return data from an image column in SQL Server. The JSON.net data table converter quite happily picks this up as a byte array and base64 encodes it. The problem occurs at the client side where the same converter simply picks up this value and treats it as a string, causing problems when the the consumer of my project is expecting it to be a byte array.

I thought I might be able to use the TypeNameHandling.All option on the serializer, but the data table converter doesn't expect to get tokens of type JsonToken.StartObject as part of the body of a DataTable .

Given that I have no control over the queries that are run, what data types are expected to be returned and no control over how they're consumed, is there anything I can do to successfully pass a byte array as part of a data table with JSON.net?

The underlying issue with default converter is that it's trying to imply the data types based purely on the data. I didn't realise at the time I asked the question, but I do also need to make sure that I can get exactly the same data table when I deserialise as I had on my server.

So my solution was to create my own implementation of the converter for DataSet and DataTable . The JSON it outputs is not nearly as pretty as that created by the default, but if you're transferring more than 1 row of data it should produce more compact JSON. The code is too big to meaningfully post on SO, so I've put the full project on GitHub .

Easiest way to solve this is converting this base64 encoded string in to byte [] in client.

string myPicture= dataRow["MY_PICTURE"].ToString();
myPicture= myPicture.Replace(" ", "+"); //Optional
byte[] myPictureInByte = Convert.FromBase64String(myPicture);

The second line is optional. I got base64 encoded string without "+" when deserialized in client. So I added them back to string and converted into byte [] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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