簡體   English   中英

如何使用Json文件作為webapi的數據源

[英]How to use Json File to serve as a data source for webapi

我想使用 Json 文件作為數據源,使用 webapi 從 Json 文件中檢索數據。

在控制器中,我添加了以下代碼:

Public HttpResponseMessage Get()
{
    var json = File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data\Bim.Json"));

      return new HttpResponseMessage()
    {
        Content = new StringContent(json, Encoding.UTF8, "application/json"),
        StatusCode = HttpStatusCode.OK
    };
}

在模型中,

public class bimModel
{
    public string name { get; set; }
    public string material { get; set; }
    public string tag { get; set; }
    public string contentType { get; set; }
}

實際上,我想使用位於 app_data 文件夾中的 json 文件,如何從 JSON 文件讀取數據? 我是 webApi 的新手,所以如果專家們可以發布整個工作代碼或盡可能多的細節,那將會很有幫助。

如果我是正確的,我相信您想將 json 文本文件反序列化為模型類,然后為客戶端將它們序列化回 json。

為此,您可以使用https://www.nuget.org/packages/newtonsoft.json/來幫助您。 按照說明安裝軟件包。

完成后,您可以編寫一個函數,例如

public bimModel Get()
{
    var json = File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data\Bim.Json"));
    var model = JsonConvert.DeserializeObject<bimModel>(json);

    return model;
}

如果您的 json 文件是bimModels的數組,那么您可以將DeserializeObject的返回類型和類型參數更改為List<bimModel>

為確保您的服務器將 json 返回給客戶端,請確保您的WebApiConfig類使用JsonMediaTypeFormatter

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();
    config.Formatters.Clear();
    config.Formatters.Add(new JsonMediaTypeFormatter());
    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
}

當然,一定要包括using Newtonsoft.Json; using Newtonsoft.Json.Serialization;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM