[英]How to convert a JSON array into a C# List?
I'm serialising an object into a JSON string in order to store it in a cookie. 我正在将一个对象序列化为JSON字符串,以便将其存储在cookie中。 The object looks like this:
该对象如下所示:
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; }
}
I would then like to be able to retrieve the object from the cookie as a JSON string, and decode it back into an object of type ShoppingCart
, with its items correctly deserialised. 然后,我希望能够从cookie中以JSON字符串的形式检索对象,并将其解码回
ShoppingCart
类型的对象,并正确反序列化其项目。
This is the code I'm using to do this: 这是我用来执行此操作的代码:
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);
}
}
Note that storing the cookie works beautifully. 请注意,存储cookie的工作方式很漂亮。 It has the correct name, and the JSON string looks good to me;
它具有正确的名称,并且JSON字符串对我来说看起来不错; here's an example:
这是一个例子:
{"Items":[{"Identifier":1,"Type":1}]}
The problem is, when I try to deserialise this, I think it's not recognising that the array is actually a List<ShoppingCartItem>
and so I end up with an instance of the ShoppingCart
class with the Items property set to an empty List<ShoppingCartItem>
. 问题是,当我尝试反序列化时,我认为它没有意识到该数组实际上是一个
List<ShoppingCartItem>
,因此我最终得到了ShoppingCart
类的实例,并将Items属性设置为空的List<ShoppingCartItem>
。
Does anyone know how I can make this work? 有谁知道我该怎么做? I'd prefer to continue using the standard
System.Web.Helpers.Json
for this if possible, but if a more robust JSON serialiser is required I'm willing to do that. 如果可能的话,我宁愿继续使用标准的
System.Web.Helpers.Json
,但是如果需要更强大的JSON序列化程序,我愿意这样做。
您需要显式转换类型,即
return Json.Decode<ShoppingCart>(value);
Similar question has been asked earlier, Using Newtonsoft JsonConvert.DeserializeObject
works well for the purpose, check the following links. 前面已经问过类似的问题,使用Newtonsoft
JsonConvert.DeserializeObject
可以很好地实现此目的,请检查以下链接。 You may even consider Javascriptserializer 您甚至可以考虑使用Javascriptserializer
How to convert Json array to list of objects in c# 如何将Json数组转换为C#中的对象列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.