c# 反序列化 JSON web api 响应

标签 c# json response asp.net-web-api

我需要一些可以告诉我我的错误在哪里的人的帮助。
我有一个返回 JSON 代码的 API:

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

我试图反序列化它但没有成功。我正在使用 NuGet 的 NewtonSoft.Json。这是我的代码:

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

namespace ConsoleApplication37
{
    class Program
    {

        class MyData
        {
            public long id { get; set; }
            public string name { get; set; }
            public int profileIconId { get; set; }
            public long revisionDate { get; set; }
            public long summonerLevel { get; set; }
        }

        static void Main()
        {
            WebRequest request = WebRequest.Create(
              "https://eune.api.pvp.net/api/lol/eune/v1.4/summoner/by-name/Block4o?api_key=****");
            request.Credentials = CredentialCache.DefaultCredentials;
            WebResponse response = request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            Console.WriteLine(responseFromServer);
            reader.Close();
            response.Close();
            Console.ReadKey();

            MyData tmp = JsonConvert.DeserializeObject<MyData>(responseFromServer);
            Console.WriteLine("{0}",tmp.id);
            Console.ReadKey();
        }

    }
}

P.S 如果响应是这样的,它就可以工作:

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

最佳答案

您需要指定您的 json 的哪个属性对应于您的模型。

MyData tmp = JsonConvert.DeserializeObject<MyData>((JObject.Parse(responseFromServer)["block4o"]).ToString());

关于c# 反序列化 JSON web api 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25485707/

相关文章:

c# - ObjectDisposedException 使用 MD5 ComputeHash 时

c# - 什么是数字串

json - 确保数组中的项目属性在 Json Schema 中是唯一的?

javascript - 如何将 JSON 转换为另一个 JSON

javascript - axios响应错误: certificate has expired

C# JIT 编译和 .NET

c# - 如果 autoreset 设置为 false,我的计时器会自动处理吗?

java - Wiremock - 验证唯一的 JSON 是否符合预期?

php - Codeigniter REST API 耗时

spring - 如何在 springdoc Schema 中描述标准的 Spring 错误响应?