【问题标题】:Getting data from JSON file and using it in c#从 JSON 文件中获取数据并在 C# 中使用它
【发布时间】:2014-08-23 09:39:05
【问题描述】:

我想制作一个程序,从 API 生成的 JSON 文件中读取一些数据。
这是该 JSON 文件的示例:

{"block4o": {
   "id": 20153910,
   "name": "Block4o",
   "profileIconId": 616,
   "revisionDate": 1408783284000,
   "summonerLevel": 30
}}

我需要做的是从中获取例如 id 和名称。 到目前为止,这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.IO;
using System.Net;


namespace ConsoleApplication30
{
    class Program
    {
        static void Main(string[] args)
        {
        }
        public void HowToMakeRequestsToHttpBasedServices()
        {
            Uri serviceUri = new Uri("https://eune.api.pvp.net/api/lol/eune/v1.4/summoner/by-name/Block4o?api_key=****");
            WebClient downloader = new WebClient();
            downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
            downloader.OpenReadAsync(serviceUri);
        }

        void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Stream responseStream = e.Result;
                // Continue working with responseStream here...
            }
        }
    }
}

任何想法都将不胜感激:)

【问题讨论】:

    标签: c# json api stream


    【解决方案1】:

    您可以使用 NuGet 安装 Newtonsoft.Json 并像这样编写:

    if (e.Error == null)
    {
        string text = e.Result;
        var events = JsonConvert.DeserializeObject<List<Event>>(text);
    }
    

    我的代码使用我的类事件并从 JSON 字符串中获取事件列表

    最好使用 Newtonsoft.Json 而不是内置库,因为您不能使用它们是一些现代项目类型(例如 windows phone 应用程序)

    ------------更新

    你可以创建类:

    public class Block
    {
        public int id;
        public string name;
        public int profileIconId;
        public int revisionDate;
        public int summonerLevel;
    }
    
    public class BlockWrapper
    {
        public Block block4o;
    }
    //...
    BlockWrapper blockWrapper = JsonConvert.DeserializeObject<BlockWrapper>(text);
    

    【讨论】:

    • 我已经从 NuGet 安装了 newtonsoft.json,但是你能告诉我如何使用这个“我的班级事件并获取事件列表”吗?我在 c# 中有点新,所以如果它很愚蠢,请原谅我的问题
    • link 当我构建程序时。它会打开一个控制台一秒钟,然后将其关闭。可能是什么问题?
    • 我不确定,但我认为 OpenReadCompletedEventHandler 不是你需要的东西。我正在使用 DownloadStringCompleted,更改 WebClient 对象的事件并将处理程序更改为 DownloadStringCompletedEventHander。我认为,您的回调仅适用于正确打开文件
    • client.DownloadStringAsync(new Uri()) 添加回调后
    • 祝你好运 :) 还有一个想法 - 使用 WebClient 时缓存存在一些问题。您将看到您更改了服务器数据,但请求者得到了相同的结果。您可以添加诸如“?nocache = randomdouble” ot url之类的smth来避免它
    猜你喜欢
    • 2021-11-10
    • 2021-03-12
    • 1970-01-01
    • 2012-05-27
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    相关资源
    最近更新 更多