Zack Antony Bucci
Zack Antony Bucci

Reputation: 591

C# Json Deserialize to generic object

I have a function with its own object type:

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

I want to use a generic function which they will all use. I want it to be generic and deserialize the object to it's type that I'm sending. I currently have:

    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;
    }

I get the error when trying to deserialize a list:

JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[tf_gsa_client.Models.HorseRacing.RaceJson]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Thanks.

Upvotes: 0

Views: 4757

Answers (1)

Grabofus
Grabofus

Reputation: 2034

You need to specify the generic type when calling your method:

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);
}

Upvotes: 5

Related Questions