yellowborat yellowborat - 6 months ago 91
JSON Question

WebApi read exsisting JSON file - C#

I am trying to create a webapi that reads an exsisting JSON file and then returns it as json object so i can use Javascript to populate the data as HTML to this site. http://pptlbhweb.azurewebsites.net/

The JSON file gets updated as i have a temperaturelogger that logs the events to an eventhub - Streamanalytics - saves as JSON in blob storage (Azure)

Here is the JSON file: https://pptlbhstorage.blob.core.windows.net/temperature/0_7622a22009224c78a46c0b2bc0a3fd82_1.json

If you look on the JSON file it needs to append "]" at the end (This is what i think) in this way i can get a valid JSON object that the WebApi returns.

I have already created a WebApi so i can use URL to get data. http://pptlbhwebapi.azurewebsites.net/api/test

Something similar for getting temperature would be for example:
http://pptlbhwebapi.azurewebsites.net/api/temperature

The fix:

Add this to your api controller:

[System.Web.Http.Route("api/readandreturnjson")]
[System.Web.Http.HttpGet]
public async Task<IHttpActionResult> ReadAndReturnJsonAsync()
{
// object to return through the API (it'll be serialized by WebAPI)
object obj = null;
// WebClient used to download the JSON file
using (var wc = new WebClient())
{

var url =
"https://pptlbhstorage.blob.core.windows.net/temperature/0_7622a22009224c78a46c0b2bc0a3fd82_1.json";
// Used to hold and add a ']' to the downloaded JSON
StringBuilder builder = new StringBuilder();
builder.Append(await wc.DownloadStringTaskAsync(url));
builder.Append("]");
// Deserialize the now valid JSON into obj
obj = JsonConvert.DeserializeObject(builder.ToString());
}
// return the json with 200 Http status.
return Ok(obj);
}


In Global.assax:

GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configu‌​ration.Formatters.XmlFormatter);

Answer

You could do this:

[System.Web.Http.Route("api/readandreturnjson")]
[System.Web.Http.HttpGet]
public async Task<IHttpActionResult> ReadAndReturnJsonAsync()
{
    // object to return through the API (it'll be serialized by WebAPI)
    object obj = null;
    // WebClient used to download the JSON file
    using (var wc = new WebClient())
    {

        var url =
        "https://pptlbhstorage.blob.core.windows.net/temperature/0_7622a22009224c78a46c0b2bc0a3fd82_1.json";
        // Used to hold and add a ']' to the downloaded JSON
        StringBuilder builder = new StringBuilder();
        builder.Append(await wc.DownloadStringTaskAsync(url));
        builder.Append("]");
        // Deserialize the now valid JSON into obj
        obj =  JsonConvert.DeserializeObject(builder.ToString());
    }
    // return the json with 200 Http status.
    return Ok(obj);
}
Comments