2

I need a little help from somebody who can tell me where my mistake is.
I have an API which returns JSON code:

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

I tried to desearialize it but without success. I am using NewtonSoft.Json from NuGet. Here is my code:

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 It works if the response is like this:

{
   "id": 20153910,
   "name": "Block4o",
   "profileIconId": 616,
   "revisionDate": 1408967362000,
   "summonerLevel": 30
}
2
  • 3
    Paste your json to json2csharp.com and see how your classes should be declared. Commented Aug 25, 2014 at 12:24
  • Heimerdinger would know how to do it :) Commented Aug 19, 2015 at 22:38

2 Answers 2

6

You need to specify which property of your json corresponds to your model.

MyData tmp = JsonConvert.DeserializeObject<MyData>((JObject.Parse(responseFromServer)["block4o"]).ToString());
Sign up to request clarification or add additional context in comments.

Comments

2

If you define the class

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

and deserialize as Response, you should get the desired result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.