【问题标题】:C# Json Deserialize to generic objectC# Json 反序列化为通用对象
【发布时间】:2020-02-17 09:16:17
【问题描述】:

我有一个具有自己对象类型的函数:

public RaceJson GetLatestRace()
{
     string filter = "example";
     List<RaceJson> currentRace = await gsaClient.SendCustomRequest<List<RaceJson>>("races?$filter=" + filter);
     return currentRace.FirstOrDefault();
}

我想使用他们都会使用的通用函数。我希望它是通用的,并将对象反序列化为我发送的类型。我目前有:

    public async Task<T> SendCustomRequest<T>(string odataFilter)
    {
        string response = await SendRequestAsync(odataFilter, true);

        if( !string.IsNullOrEmpty(response))
        {
            T converted = JsonConvert.DeserializeObject<T>(response);
            return converted;
        }

        return default;
    }

尝试反序列化列表时出现错误:

JsonSerializationException: 无法反序列化当前 JSON 对象 (例如 {"name":"value"}) 转换为类型 'System.Collections.Generic.List`1[tf_gsa_client.Models.HorseRacing.RaceJson]' 因为该类型需要一个 JSON 数组(例如 [1,2,3])来反序列化 正确。要修复此错误,请将 JSON 更改为 JSON 数组 (例如 [1,2,3])或更改反序列化类型,使其成为正常的 .NET 类型(例如,不是像整数这样的原始类型,也不是集合 可以从 JSON 反序列化的数组或列表等类型 目的。 JsonObjectAttribute 也可以添加到类型中来强制它 从 JSON 对象反序列化。

谢谢。

【问题讨论】:

标签: c# json object serialization types


【解决方案1】:

调用方法时需要指定泛型类型:

public string GetRace()
{
     string filter = "example";
     RaceJson currentRace = await gsaClient.SendCustomRequest<RaceJson>("races?$filter=" + filter);
}

public string GetPeople()
{
     string filter = "example";
     List<PeopleJson> currentPeople = await gsaClient.SendCustomRequest<List<PeopleJson>>("people?$filter=" + filter);
}

【讨论】:

  • 谢谢。已解决问题。但是,如果它不反序列化,我想返回“null”。它说我必须返回默认值。这是同一件事吗?
  • 如果 &lt;T&gt; 不是可以为空的引用类型,您可能无法返回 null。例如SendCustomRequest&lt;int&gt; 的默认值为0
  • 我认为您可以放心地使用default,因为您使用的是 JSON 对象,而不是原始值。
  • 看来,如果我尝试将类型用作列表,例如> 我在运行时遇到错误。我已经用错误更新了我的问题。无论如何,我相信大多数 Json 都会在列表中返回。
  • 您可能应该为此创建一个单独的问题......并发布您的数据样本。如果您更改问题,面临相同问题的人将无法理解给出的答案。 :)
猜你喜欢
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多