c# - 如何将 JSON 数组转换为 C# 列表?

标签 c# json asp.net-mvc cookies

我正在将对象序列化为 JSON 字符串,以便将其存储在 cookie 中。该对象看起来像这样:

public class ShoppingCart
{
    public List<ShoppingCartItem> Items { get; set; }

    public ShoppingCart()
    {
        Items = new List<ShoppingCartItem>();
    }
}

public class ShoppingCartItem
{
    public enum ShoppingCartItemType
    {
        TypeOfItem,
        AnotherTypeOfItem
    }
    public int Identifier { get; set; }
    public ShoppingCartItemType Type { get; set; }
}

然后我希望能够从 cookie 中检索对象作为 JSON 字符串,并将其解码回类型为 ShoppingCart 的对象,其项目已正确反序列化。

这是我用来执行此操作的代码:

public class CookieStore
{
    public static void SetCookie(string key, object value, TimeSpan expires)
    {
        string valueToStore = Json.Encode(value);
        HttpCookie cookie = new HttpCookie(key, valueToStore);

        if (HttpContext.Current.Request.Cookies[key] != null)
        {
            var cookieOld = HttpContext.Current.Request.Cookies[key];
            cookieOld.Expires = DateTime.Now.Add(expires);
            cookieOld.Value = cookie.Value;
            HttpContext.Current.Response.Cookies.Add(cookieOld);
        }
        else
        {
            cookie.Expires = DateTime.Now.Add(expires);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
     }
    public static object GetCookie(string key)
    {
        string value = string.Empty;
        HttpCookie cookie = HttpContext.Current.Request.Cookies[key];

        if (cookie != null)
        {
            value = cookie.Value;
        }
        return Json.Decode(value);
    }

}

请注意,存储 cookie 的效果非常好。它有正确的名称,而且 JSON 字符串对我来说看起来不错;这是一个例子:

{"Items":[{"Identifier":1,"Type":1}]}

问题是,当我尝试反序列化它时,我认为它没有识别出数组实际上是一个 List<ShoppingCartItem>。所以我最终得到了一个 ShoppingCart 的实例Items 属性设置为空的类 List<ShoppingCartItem> .

有谁知道我该怎么做?我宁愿继续使用标准 System.Web.Helpers.Json如果可能的话,但如果需要更强大的 JSON 序列化程序,我愿意这样做。

最佳答案

需要显式转换类型,即

return Json.Decode<ShoppingCart>(value);

关于c# - 如何将 JSON 数组转换为 C# 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30771199/

相关文章:

java - 上传带有嵌套数组的 jaxb bean 返回状态 400

python (gspread) - 整个数据表放置在我的 Google Sheets 的一个单元格中,而不是单独的单元格中

c# - 静态类优缺点

c# - 如何将下拉列表项设置为在 ASP.NET 中选中?

c# - 使用 WMI : How can I get the name of the user account who's running my program?

json - 带有 json 和非 json 列的 pyspark 读取文件

asp.net-mvc - Kendo网格层次结构的问题

javascript - 为什么 ajax 调用没有按指定的延迟进行

asp.net - ASP.NET vNext 如何处理 config.json 中的缓存、压缩和 MimeMap?

c# - 将 AvalonEdit 绑定(bind)到 XML