0

I have a C# API which is currently used by a number of our websites. My API is sent a JSON request, I do some stuff based on the details in that request, then send a JSON response with the outcome of the API's work, and some other information.

I now need to do include some extra information in my JSON response.

I need to read a file in from a specific Url (this file may be an image, a MS word doc, a PDF etc. - could be anything really).

I already know the mime type of this file at the url (so as to determine whether it's valid for me to process or not).

If it's a supported file/mime type, I want to retrieve this file from the specified url and ultimately convert it/serialize it to JSON and include it within my JSON response.

In some cases, I may actually have multiple files/urls that I need to retrieve, convert and include within my JSON response (ideally as an array, inside a property called 'Attachments').

I've used Newtonsoft.Json for serializing and deserializing classes with regular properties before, but not done anything with reading in files and sending them as JSON, and can't find any clear examples of how to go about this.

marcusstarnes
  • 6,393
  • 14
  • 65
  • 112

2 Answers2

0

Consider a file data as a byte array. Then it can be serialized in JSON with your Data Transfer Object.

public class YourTDO {

    ...some other properties...

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

Read the file as a byte array from your external source, assign FileData properties and serialize your object as usual.

Sergey L
  • 1,402
  • 1
  • 9
  • 11
0

You can use your API to serve the files directly and only provide an identifier in the JSON. Depending on what you are trying to do with the static content (assuming your PDF, etc, are static) you could also host the files on AWS and have the identiefier be the unique link to the files.

In most cases you JSON objects are some kind of object that you are passing around, and in some cases you may reference the same files. Separating the content delivery also gives you a better chance to monitor and tweak performance.