从JSON文件中获取数据并在c#中使用它

本文关键字:数据 JSON 文件 获取 | 更新日期: 2023-09-27 18:19:08

我想编写一个程序,从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...
            }
        }
    }
}

从JSON文件中获取数据并在c#中使用它

可以安装Newtonsoft。使用NuGet Json,并像这样写smth:

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