【发布时间】:2021-12-17 17:48:50
【问题描述】:
我有这个方法:
public static class SessionExtension
{
public static void SetObjectAsJson(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetObjectFromJson<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
}
这对序列化我的 IEnumerable 列表很有用:
public IEnumerable<FBudget> RecordsList { get; set; }
所以过滤数据后我序列化对象:
//BUILD FILTER
static Expression<Func<FBudget, bool>> BuildFilter(BudgetViewModel budget)
{
...
}
/*STORE THE ACTUAL FILTER IN SESSION*/
SessionExtension.SetObjectAsJson(HttpContext.Session, "SessionFilter", budget);
反序列化它:
public IActionResult Index()
{
var json = SessionExtension.GetObjectFromJson<IEnumerable<FBudget>>(HttpContext.Session, "SessionFilter");
BudgetVM = new BudgetViewModel()
{
FBudget = new FBudget(),
...
RecordsList = json
};
return View(BudgetVM);
}
但是当我尝试反序列化它时,编译器会给出以下错误:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable`1[...]' 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.
Path 'FBudget', line 1, position 11.'
我也尝试这样做是为了在会话中保持BuildFilter() 方法的结果,因此当用户返回上一页时,过滤器被保存。
是正确的方法吗?我做错了什么?
这是发送到 GetObjectFromJson 方法的 Json:
{"BudgetId":0,"Year":0,"FreeOfCharge":null,"Currency":null,"UnitPrice":0.0,"MonthNr":null,"UnitOfMeasure":null,"Quantity":0,"TotalAmount":0.0,"LastUser":null,"ProgramId":0,"LastUpdate":"2021-11-03T15:08:15.65645+01:00","ItemMasterId":0,"ItemMaster":{"ItemMasterId":0,"ItemNumber":0,"ShortItem":null,"ItemDescription":null,"UnitOfMeasure":null,"FBudgets":null,"PharmaFormId":0,"PharmaForm":null,"ProductGroupId":0,"ProductGroup":null,"UnToBulkId":0,"UnToBulk":null,"UnToKgId":0,"UnToKg":null},"CompanyId":2,"Company":null,"LedgerTypeId":0,"LedgerType":null,"CustomerId":0,"Customer":{"CustomerId":0,"CustomerName":null,"CustomerGroupCode":null,"CountryCode":null,"CustomerGroupName":null,"LicensingArea":null,"FBudgets":null}}
【问题讨论】:
-
你能分享你试图反序列化的示例 json 吗?
-
从错误消息中,您似乎尝试反序列化一个 json 对象 {'name': '', 'value': ''},但它需要一个像 [ { 'name' : '', '值':'' } ]
-
@Chetan 完成!看看(我编辑了问题)
-
@AbuZafor 好的,我该怎么做?
-
您共享的 json 不代表集合,而是针对单个对象。试试
SessionExtension.GetObjectFromJson<FBudget>(HttpContext.Session...
标签: c# asp.net-mvc session serialization ienumerable