Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Parsing JSON String

Tags:

json

c#

I have tried countless methods to Parse my JSON string (Steam Public Data), yet nothing seems to work. I just want to be able to extract values from the string. For Example, obtaining the value of personaname which would return SlothGod. I have JSON.NET installed in my project.

Here is my JSON:

{
    "response": {
        "players": [
            {
                "steamid": "76561198301407459",
                "communityvisibilitystate": 3,
                "profilestate": 1,
                "personaname": "SlothGod",
                "lastlogoff": 1508389707,
                "commentpermission": 1,
                "profileurl": "http://steamcommunity.com/id/sleuthgud/",
                "avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba.jpg",
                "avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba_medium.jpg",
                "avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba_full.jpg",
                "personastate": 0,
                "realname": "Josh",
                "primaryclanid": "103582791460168790",
                "timecreated": 1462086929,
                "personastateflags": 0,
                "loccountrycode": "AU",
                "locstatecode": "QLD"
            }
        ]

    }
}

Main method suggested to me:

public class Details
{
    public string personaname { get; set; }
}
private void GetSteamDetails()
{
    var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Details>(SteamDetailsJson);
    SteamName = data.personaname;
}

This is placed before Page_Load(). I then call GetSteamDetails(); when I want to fetch the name.

like image 892
SlothGod Avatar asked Sep 10 '25 10:09

SlothGod


1 Answers

After my question being down voted, I decided to not give up on this problem. After extensive research, trial and error, and YouTube tutorials which are the most helpful IMO. I found that the data was containing a JSON array, and yes I will admit, I was confused with this, but the answer was to simply treat it like a C# array and add [1] to the end of players.

Details details = new Details();
public class Details
{
    public string avatar { get; set; }
    public string avatarmedium { get; set; }
    public string avatarfull { get; set; }
    public string realname { get; set; }
    public string personaname { get; set; }
    public string steamid { get; set; }
}

private void GetSteamDetails()
{
    var SteamDetails= JsonConvert.DeserializeObject<dynamic>(SteamDetailsJson);
    avatar = SteamDetails.response.players[1].avatar.ToString();
    personaname = SteamDetails.response.players[1].personaname.ToString();
}
like image 118
SlothGod Avatar answered Sep 13 '25 01:09

SlothGod