0

Database table has stored document in varbinary.

So i can get in byte[] in C# code.

Now How can i export this byte[] JSON file field.

if (item.IS_VIDEO == 0)
{
    var content = ctx.DOCUMENT_TABLE.First(a => a.document_id == item.document_id).DOCUMENT_CONTENT;
    if (content != null)
    {
        publicationClass.document_content = System.Text.Encoding.Default.GetString(content); //for export to json field
    }
}

is this a way to export byte[] file to JSON?

sangram parmar
  • 8,462
  • 2
  • 23
  • 47
  • Over 600 people agreed that this is the way to do it here: http://stackoverflow.com/questions/11654562/how-convert-byte-array-to-string – J. Tuc Feb 27 '17 at 13:21
  • @J.Tuc you are right but i want to send this string in json file..so is this way is correct? that i would like to know – sangram parmar Feb 27 '17 at 13:25
  • Actually, the answer to that question is pretty way off in the general sense. There is no guarantee that any random byte array contains anything that a string decoder can safely turn into a string so it all depends on what is *in* those bytes. If it is actually a string encoded into bytes, then yes, using the right encoder to then decode the bytes back into a string should work, otherwise you probably want to encode the byte array using Base64 or similar algorithm to safely turn it into a string. – Lasse V. Karlsen Feb 27 '17 at 13:50
  • However, if you simply give a byte array to Json.Net, it will do the "right thing" out of the box so the very first question that needs to be answered is if there is a need to do anything at all. Make `document_content` a byte array property and let Json.Net handle the details. **Does that work?** – Lasse V. Karlsen Feb 27 '17 at 13:51
  • Now, having said that, are you sure this is the right thing to do regardless of how you end up getting it into a string? A *video* tends to be fairly large and wrapping it in a text format that will increase the size will most likely tax even the best json decoder in terms of memory usage. Or is `IS_VIDEO == 0` mean that it is *not* a video? – Lasse V. Karlsen Feb 27 '17 at 13:53
  • @LasseV.Karlsen yes it is not a video – sangram parmar Mar 01 '17 at 07:03

1 Answers1

0

Have you considered letting JSON serializer deal with the problem?

byte[] file = File.ReadAllBytes("FilePath"); // replace with how you get your array of bytes
string str = JsonConvert.SerializeObject(file);

This can be then deserialized on the receiving end like this:

var xyz = JsonConvert.DeserializeObject<byte[]>(str);

This appears to be working without any issues, however there might be some size limitations that might be worth investigating before commiting to this method.

J. Tuc
  • 424
  • 2
  • 10