簡體   English   中英

在Session中序列化和反序列化一個IEnumerable

[英]Serialize and deserialize an IEnumerable in Session

我有這個方法:

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 是一個對象而不是數組,對於反序列化,請嘗試以下代碼:

public IActionResult Index()
{
    var json = SessionExtension.GetObjectFromJson<FBudget>(HttpContext.Session, "SessionFilter");

    BudgetVM = new BudgetViewModel()
    {
        FBudget = new FBudget(),
        ...
       
        RecordsList = new List<FBudget> { json }
    };

    return View(BudgetVM);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM