JsonConvert.DeserializeObject Problem when use for generic types!

  • Thread starter Thread starter Hamed_1983
  • Start date Start date
H

Hamed_1983

Guest
Hi

I'm using this code to deserialize my json data to list of objects as follow :

public static List<T> DeserializeListFromTempData<T>(HttpContext context, string strName)
{
List<T> lstResult = null;

var iTempData = HelperMethods.GetTempData(context);
var tmp = iTempData.Peek(strName);
if (tmp != null)
{
lstResult = JsonConvert.DeserializeObject<List<T>>(tmp.ToString(), new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
}

return lstResult;
}

And usage :

List<DefaultVisitProductDetails> lstPackageDetails = HelperMethods.DeserializeListFromTempData<DefaultVisitProductDetails>(this.HttpContext, "_lstPackageDetails");

The above codes works correctly. However, when i use it inside another generic method as follow :

public static void AttachDetailsListToDbContext<T, TDetails, TField>(HttpContext context, string strName, DbContext dbContext, object masterObjectGraph, Expression<Func<T, TDetails>> details, Expression<Func<T, TField>> field, TField value, InternalHelperAction action) where T : class
{
List<TDetails> lstPackageDetails = HelperMethods.DeserializeListFromTempData<TDetails>(context, strName);
...
}

i'm facing the following problem :

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.ICollection`1[EFCoreTest.Models.DefaultVisitProductDetails]' 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<T>) 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.

Where is the problem & how to solve it?

Thanks in advance





Database Helper v 2.0.0

Continue reading...
 
Back
Top