I am trying to get everything below apps and put the values inside a Dictionary<string, Games>
I am using the below code.
Class:
public class Games
{
public int AppId { get; set; }
public string Name { get; set; }
}
Code:
public Dictionary<string, Games> GetAllGames()
{
//http://api.steampowered.com/ISteamApps/GetAppList/v0002/?key=STEAMKEY&format=json
var url = "http://api.steampowered.com/ISteamApps/GetAppList/v0002/?key=STEAMKEY&format=json";
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(url));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
var t = JObject.Parse(jsonString).SelectToken("applist").ToString();
var s = JObject.Parse(t).SelectToken("apps").ToString();
Dictionary<string, Games> gamesList = JsonConvert.DeserializeObject<Dictionary<string, Games>>(s);
return gamesList;
}
Error:
Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,LudumPricer.Games]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
JSON sample:
{
"applist":{
"apps":[
{
"appid":5,
"name":"Dedicated Server"
},
{
"appid":7,
"name":"Steam Client"
},
{
"appid":8,
"name":"winui2"
},
{
"appid":10,
"name":"Counter-Strike"
}
]
}
}
I want to get everything under the apps
attribute and put them in a Dictionary <string, Games>
I am using the newtonsoft json.net library
Just convert and use ToDictionary
Given
public class App
{
public int appid { get; set; }
public string name { get; set; }
}
public class Applist
{
public List<App> apps { get; set; }
}
public class RootObject
{
public Applist applist { get; set; }
}
Usage
var root = JsonConvert.DeserializeObject<RootObject>(jsonString);
var dict = root.applist.apps.ToDictionary(x => x.appid, x => x.name);
Enumerable.ToDictionary Method (IEnumerable, Func)
Creates a Dictionary from an IEnumerable according to a specified key selector function.
User contributions licensed under CC BY-SA 3.0