为什么反序列化返回null?

问题描述 投票:0回答:2

我正在尝试反序列化来自 C# .NET 7 中的 SteamAPI 的响应。我通过 RestSharp 发出 REST 请求并将内容保存为文件。

后来我加载该文件并想反序列化它以使用 LINQ 搜索它。但是使用 JsonSerializerOptions 的各种选项,它不起作用。

SteamAppList.AppList
始终为空。

对于数据模型,我使用了 Json2Csharp 和 Jetbrains Rider。

我尝试了不同的

JsonSerializerOptions
,并通过 VS Code 和 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 library 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
类:

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."
        }
    ]
}
}
c# json .net-core
2个回答
1
投票

我对模型进行了更多的研究并找到了解决方案。 这是配套型号:

public class SteamAppList
{
    [JsonPropertyName("applist")]
    public Applist Applist { get; set; }
}

public class Applist
{
    [JsonPropertyName("apps")]
    public App[] Apps { get; set; }
}

public class App
{
    [JsonPropertyName("appid")]
    public long Appid { get; set; }

    [JsonPropertyName("name")]
    public string? Name { get; set; }
}

1
投票

您的反序列化失败,因为您的模型具有字段,并且默认情况下字段被忽略。您有两个选择:

  • 将字段更改为模型中的属性

  • [JsonInclude]
  • 注释字段
© www.soinside.com 2019 - 2024. All rights reserved.