问题描述
我正在使用一些Json数据,其中的AppID具有一个字段。显然,此AppID会根据我要查询的应用程序而变化。因此,在网上搜索时,我发现可以使用自定义转换器来执行此任务,但是我的实现似乎失败了,我不确定为什么。具体来说,当尝试打印从Json反序列化的数据返回null时,它将失败。我的模型(经过整理)如下。
public partial class SteamAPIModel
{
[JsonProperty("AppIDJson")]
[JsonConverter(typeof(AppIDConverter))]
public AppIDJson AppIDJson { get; set; }
}
public partial class AppIDJson
{
[JsonProperty("success")]
public bool success { get; set; }
public Data data { get; set; }
}
public partial class Data
{
public string name { get; set; }
public string short_description { get; set; }
}
public class AppIDConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(AppIDJson);
}
public override object ReadJson(JsonReader reader,Type objectType,object existingValue,JsonSerializer serializer)
{
//This int value here is declared in another class and accessed this way.
return apiTask.ApplicationIDAPITask;
}
public override void WriteJson(JsonWriter writer,object value,JsonSerializer serializer)
{
serializer.Serialize(writer,value);
}
就该模型而言,按照我所知的标准来看,除了访问我希望成为另一个类的属性名称的实际名称之外,其他所有内容均如此。下面声明了哪个类,为了清楚起见,我将包括我的API调用。
public class apiTask
{
public static int ApplicationIDAPITask { get; set; }
public static void Runner(int ApplicationIDSource)
{
ApplicationIDAPITask = ApplicationIDSource;
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://store.steampowered.com/api/appdetails/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//in the below URL I do have a token in the final project to allow the number of queries needed for the project
HttpResponseMessage response = await client.GetAsync("&appids="+ ApplicationIDAPITask).ConfigureAwait(false);
if (response.IsSuccessstatusCode)
{
string httpResponseBody = await response.Content.ReadAsstringAsync();
SteamAPIModel game_item = JsonConvert.Deserializedobject<SteamAPIModel>(httpResponseBody);
if (game_item.AppIDJson != null)
{
Debug.WriteLine(game_item.AppIDJson.success.ToString());
} else
{
//This is what executes currently,never completing the code in the if statement,}
}
}
}
}
虽然可能是一些意大利面条代码,但是这里的想法是我可以调用apiTaks.Runner(App ID);使用任何有效的AppID,然后将使用其中的那个AppID发出API请求,当API请求获得该AppID的结果后,它将能够使用动态名称正确解码Json。因为在Raw Json中,第一个字段是AppID int本身。最后,我希望显然可以像在ApiTask.cs中使用Print语句一样引用该数据。
最后是确保我在下面提供了返回的Json数据中足够的信息...
{
"730": {
"success": true,"data": {
"type": "game","name": "Counter-Strike: Global Offensive","steam_appid": 730,"required_age": 0,"is_free": true,"controller_support": "full",..........
当前,如果我改为将“ AppIDJson”标记为特定的AppID并对该特定的AppID进行查询,则一切按预期运行,因此此代码的其余部分均正常运行,我只想将其包括在内,以帮助进行故障排除我的问题是。感谢您在此问题上的任何帮助,如果您发现我的代码中还有其他可以改进的地方,因为在此项目中几乎所有新内容对我来说都是如此。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)