WebApi读取现有的JSON文件 - C#

时间:2016-05-26 12:25:53

标签: javascript c# json azure asp.net-web-api

我正在尝试创建一个webapi,它读取一个现有的JSON文件,然后将其作为json对象返回,这样我就可以使用Javascript将数据填充为HTML到此站点。 http://pptlbhweb.azurewebsites.net/

JSON文件得到更新,因为我有一个将事件记录到eventhub的温度记录器 - Streamanalytics - 在blob存储中保存为JSON(Azure)

以下是JSON文件:https://pptlbhstorage.blob.core.windows.net/temperature/0_7622a22009224c78a46c0b2bc0a3fd82_1.json

如果您查看JSON文件,则需要附加"]"在最后(这是我的想法),通过这种方式,我可以获得WebApi返回的有效JSON对象。

我已经创建了一个WebApi,所以我可以使用URL来获取数据。 http://pptlbhwebapi.azurewebsites.net/api/test

类似于获得温度的东西将是例如: http://pptlbhwebapi.azurewebsites.net/api/temperature

修复:

将此添加到您的api控制器:

[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);
}

在Global.assax中:

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

1 个答案:

答案 0 :(得分:0)

你可以这样做:

[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);
}