繁体   English   中英

c#反序列化JSON web api响应

[英]c# deserializing JSON web api response

我需要一些可以告诉我错误在哪里的人的帮助。
我有一个返回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();
        }

    }
}

PS它的工作原理如果响应是这样的:

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

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

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

如果你定义了这个类

public class Response
{
  public MyData Block4o { get; set; }
}

并反序列化为响应,您应该得到所需的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM