【问题标题】:How i can use a json file in a webservice c#我如何在 web 服务 c# 中使用 json 文件
【发布时间】:2020-06-21 09:36:26
【问题描述】:

您好,我使用 Visual Studio 2017 创建了一个 Web 服务。

但现在我想获取一个 json 文件并在我的网络服务中显示它

我想读取像“idVersions.json”这样的文件,而不是代码中写的“idVersion”

解决方案组织示例

Sln

有人可以帮助我吗?提前谢谢你:)

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using Newtonsoft.Json;


namespace getLastVersionNumber
{
    /// <summary>
    /// Description résumée de WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // Pour autoriser l'appel de ce service Web depuis un script à l'aide d'ASP.NET AJAX, supprimez les marques de commentaire de la ligne suivante. 
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        DataTable idVersions = new DataTable();
      
       

        

        [WebMethod]
        public string idVersion()
        {
            idVersions.Columns.Add("id");
            idVersions.Columns.Add("Version");

            idVersions.Rows.Add("1", "v0.1");
            idVersions.Rows.Add("2", "v0.2");
            idVersions.Rows.Add("3", "v0.2.5");
            idVersions.Rows.Add("4", "v1.2");
            idVersions.Rows.Add("5", "v2.5");
            idVersions.Rows.Add("6", "v3");

            return JsonConvert.SerializeObject(idVersions);
        }

    }
}

【问题讨论】:

  • 您想从哪里读取文件?你能解释更多吗?
  • 读取 JSON 文件和读取文本文件一样。您读取 JSON 文件,将 JSON 反序列化为 C# 类对象,然后像您一样使用它。stackoverflow.com/questions/13297563/…
  • @viveknuna 我刚刚用图片编辑了帖子
  • @ChetanRanpariya 我会检查你的链接谢谢
  • 也许你可以通过File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + @"/test.json")之类的语句访问json文件。

标签: c# .net json visual-studio web-services


【解决方案1】:

您可以直接从源代码中读取 JSON,如下所示。

string json = "";
using (WebClient wc = new WebClient())
{
   json = wc.DownloadString("https://jsonplaceholder.typicode.com/todos/1");
}

一旦你得到 json 字符串,你就可以序列化到你的对象。

【讨论】:

  • 嗨 @vaseef 我试过你的建议,但 webclient 无法识别它是我必须下载的块包?
  • WebClient 类是命名空间 System.Net 的一部分。您可以将该行修改为“using (System.Net.WebClient wc = new System.Net.WebClient())”或添加命名空间“using System.Net;”
【解决方案2】:

使用 File.ReadAllText 并返回这个字符串?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-30
    • 2012-07-17
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多