Json to c# Objects in .NET

384 views Asked by At

I've been wanting to make my own dota 2 stats website/app. Basically, I'm using the steam API to gather all the essential data. Most of this data is stored in Json format.

I've been trying to deserialise the format so that I can have the data in a readable format. Ideally I want to turn it into objects and then put them into a data grid so I can present this data properly to the user.

Additionally, I am using the Portable Steam WebAPI Wrapper for C# and Newtonsoft packages.

Public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

   SteamWebAPI.SetGlobalKey("MysteamKey");

    var r2 =  SteamWebAPI.Game().Dota2().IDOTA2().GetHeroes().GetResponseString(RequestFormat.JSON);

    var ds1 = Newtonsoft.Json.JsonConvert.DeserializeObject(r2);
    RootObject hero = JsonConvert.DeserializeObject<RootObject>(r2);


    Response.Write("Display Hero Data.. </br></br>");
    Response.Write( hero.result.heroes );


    Response.Write(hero);


   }
}

Here is my Hero class: I basically used this website to come up with it - http://json2csharp.com/ Additionally, the Json file can be found here https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=2D13D618DA712015812E970165632F02&language=en_us

public class Hero
{
public string name { get; set; }
public int id { get; set; }
public string localized_name { get; set; }
}

public class Result
{
public List<Hero> heroes { get; set; }
public int status { get; set; }
public int count { get; set; }
}

public class RootObject
{
    public Result result { get; set; }
}

Currently, this is what is displayed from my current code:

" Display Hero Data..

System.Collections.Generic.List`1[Hero]RootObject "

It doesn't seem to display any of the data from the json file :/ I'm sure i'm missing something straighforward here, but I just can't put my finger on it :(

I really need some assistence here, If I can get this working, then I can start pulling all the other data I need. I'd appreciate any help whatsoever. Thanks in advance.

1

There are 1 answers

5
willaien On

Response.Write( hero.result.heroes );

That is just going to write out the "string" version of heroes. Since it's an object, it's just giving you List's (or Object's!) .ToString() function (which displays System.Collections.Generic.List`1[Hero]RootObject)

You're going to need to iterate over the collection. I see that you're directly writing out to the response, which I would discourage, but, if you want to see these written out with it, you can use something like this:

foreach(var hero in hero.result.heroes)
{
    Response.Write(String.Format("<p>Name: {0}, ID: {1}</p>", hero.name, hero.id)
}

Since it looks like you're messing around with webforms, I suggest you take a look at some tutorials on how to use it (or mvc)