我试图在C# .NET 7中反序列化来自SteamAPI的响应。我通过RestSharp发出REST请求,并将内容保存为文件。稍后,我加载该文件,并希望将其反序列化以使用LINQ搜索它。但是对于JsonSerializerOptions的各种选项,它不起作用。SteamAppList.AppList
始终为null。
对于数据模型,我使用了Json2Csharp和Jetbrains Rider。
我尝试了不同的JsonSerializerOptions,并通过vscode和Jetbrains Rider进行了调试。
下面是我的模型(SteamAppList.cs):
[Serializable]
public class SteamAppList
{
[JsonPropertyName("applist")]
public Applist Applist;
}
[Serializable]
public class Applist
{
[JsonPropertyName("apps")]
public List<App> Apps;
}
[Serializable]
public class App
{
[JsonPropertyName("appid")]
public int Appid;
[JsonPropertyName("name")]
public string Name;
}
以及我的SteamApps.cs,用于请求和反序列化:
public class SteamApps
{
private readonly CancellationToken cancellationToken;
private async Task<RestResponse> GetSteamApps()
{
var client = new RestClient();
var request = new RestRequest("https://api.steampowered.com/ISteamApps/GetAppList/v2/");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent", "Major GSM");
var response = await client.GetAsync(request, cancellationToken);
return response;
}
public bool RetireveAndSaveSteamApps()
{
var path = FileModule.GetDirectoryPath(MajorGsmLibrary.ApplicationDirectory.Games);
var fileName = "steam.library.json";
RestResponse restResponse = GetSteamApps().Result;
try
{
File.WriteAllText(Path.Combine(path, fileName), restResponse.Content);
}
catch (IOException exception)
{
LogModule.WriteError("Could not write steam libarary file!", exception);
return false;
}
catch (ArgumentNullException exception)
{
LogModule.WriteError("Missing data for steam library file", exception);
return false;
}
return true;
}
public static string CheckGameAgainstSteamLibraryWithAppId(string appId)
{
var path = FileModule.GetDirectoryPath(MajorGsmLibrary.ApplicationDirectory.Games);
var fileName = "steam.library.json";
var fileData =
File.ReadAllText(Path.Combine(path, fileName));
SteamAppList? steamAppList = JsonSerializer.Deserialize<SteamAppList>(fileData, new JsonSerializerOptions { MaxDepth = 64, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
if (steamAppList!.Applist != null)
{
var app = steamAppList.Applist.Apps.SingleOrDefault(x => x.Appid.ToString() == appId);
if (app != null) return app.Name;
}
return "Unknown";
}
}
我正在从GTK#应用程序调用SteamApps-class:
foreach (var game in Games)
{
var appName = SteamApps.CheckGameAgainstSteamLibraryWithAppId(game.AppId);
if (appName == "Unknown") return;
game.FoundInSteamLibrary = true;
game.SteamLibraryName = appName;
}
我收到的JSON看起来像这样:
{
"applist": {
"apps": [
{
"appid": 1941401,
"name": ""
},
{
"appid": 1897482,
"name": ""
},
{
"appid": 2112761,
"name": ""
},
{
"appid": 1470110,
"name": "Who's Your Daddy Playtest"
},
{
"appid": 2340170,
"name": "Melon Knight"
},
{
"appid": 1793090,
"name": "Blockbuster Inc."
}
]
}
}
2条答案
按热度按时间bn31dyow1#
我对模型进行了更多的研究,并找到了一个解决方案。以下是匹配模型:
bhmjp9jg2#
反序列化失败,因为模型具有字段,而默认情况下字段被忽略。您有两个选择:
或
[JsonInclude]
注解字段