简体   繁体   English

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

[英]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#中的对象列表

Deserialize JSON array(or list) in C# 在C#中反序列化JSON数组(或列表)

deserialize json array list in c# 在C#中反序列化json数组列表

如何转换列表<object>至 Json | C#<div id="text_translate"><p> 我有一个由对象组成的列表,每个 object 有 5 个数据。 我需要将该列表转换为 json,但使用序列化它会填满空的 json。</p><p> 有谁知道我可能做错了什么?</p><pre> foreach (DataRow dtRow in dtAlarmas.Rows) { String Name = dtRow["Name"].ToString(); String ID = dtRow["ID"].ToString(); String AlarmText = dtRow["AlarmText"].ToString(); String AlarmTimeNoNula = dtRow["AlarmTimeNoNula"].ToString(); lstAlarmasNoTratadas.Add(new Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel(dtRow["Name"].ToString(), Convert.ToInt32(dtRow["ID"]), dtRow["Class"].ToString(), dtRow["AlarmText"].ToString(), dtRow["AlarmTimeNoNula"].ToString())); } string sParams = JsonConvert.SerializeObject(lstAlarmasNoTratadas);</pre><p> 转换后的 sParams 值 = "[{}]"</p><p> Class Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel</p><pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ondoan.DatosAux.Alarmas { public class AlarmaNoTratadaModel { private string Name; private int ID; private string Class; private string AlarmText; private string AlarmaTimeNoNula; public AlarmaNoTratadaModel(string Name, int ID, string Class, string AlarmText, string AlarmaTimeNoNula) { // TODO: Complete member initialization this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula; } public class AlarmaNoTratadasModel { public AlarmaNoTratadasModel() { } public AlarmaNoTratadasModel(String Name, Nullable&lt;System.Int32&gt; ID, String Class, String AlarmText, String AlarmaTimeNoNula) { this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula.ToString(); } public System.String Name { get; set; } public Nullable&lt;System.Int32&gt; ID { get; set; } public System.String Class { get; set; } public System.String AlarmText { get; set; } public System.String AlarmaTimeNoNula { get; set; } } } }</pre></div></object> - How to Convert List<Object> to Json | C#

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在C#中将Json数组转换为列表 - How to convert Json array to list in c# 如何在C#中将JSON数组转换为对象列表 - How to convert JSON array into object list in the c# 如何将 Json 数组转换为 C# 中的对象列表 - How to convert Json array to list of objects in c# JSON 将数组类型转换为 C# 中的列表 - JSON convert array type to list in C# 如何将json转换为列表c# - how to convert json to list c# 如何转换列表<object>至 Json | C#<div id="text_translate"><p> 我有一个由对象组成的列表,每个 object 有 5 个数据。 我需要将该列表转换为 json,但使用序列化它会填满空的 json。</p><p> 有谁知道我可能做错了什么?</p><pre> foreach (DataRow dtRow in dtAlarmas.Rows) { String Name = dtRow["Name"].ToString(); String ID = dtRow["ID"].ToString(); String AlarmText = dtRow["AlarmText"].ToString(); String AlarmTimeNoNula = dtRow["AlarmTimeNoNula"].ToString(); lstAlarmasNoTratadas.Add(new Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel(dtRow["Name"].ToString(), Convert.ToInt32(dtRow["ID"]), dtRow["Class"].ToString(), dtRow["AlarmText"].ToString(), dtRow["AlarmTimeNoNula"].ToString())); } string sParams = JsonConvert.SerializeObject(lstAlarmasNoTratadas);</pre><p> 转换后的 sParams 值 = "[{}]"</p><p> Class Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel</p><pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ondoan.DatosAux.Alarmas { public class AlarmaNoTratadaModel { private string Name; private int ID; private string Class; private string AlarmText; private string AlarmaTimeNoNula; public AlarmaNoTratadaModel(string Name, int ID, string Class, string AlarmText, string AlarmaTimeNoNula) { // TODO: Complete member initialization this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula; } public class AlarmaNoTratadasModel { public AlarmaNoTratadasModel() { } public AlarmaNoTratadasModel(String Name, Nullable&lt;System.Int32&gt; ID, String Class, String AlarmText, String AlarmaTimeNoNula) { this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula.ToString(); } public System.String Name { get; set; } public Nullable&lt;System.Int32&gt; ID { get; set; } public System.String Class { get; set; } public System.String AlarmText { get; set; } public System.String AlarmaTimeNoNula { get; set; } } } }</pre></div></object> - How to Convert List<Object> to Json | C# 如何在 C# 中将列表转换为 JSON? - How to convert a list to JSON in C#? 如何在C#中将JSON响应转换为列表? - How to convert JSON Response to a List in C#? 如何在c#中将Json字符串转换为List - How to convert a Json string to List in c# 如何在 c# 中将列表转换为 json - How to convert list to json in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM