简体   繁体   English

如何从json数组创建List集合?

[英]How do i create a List collection from a json array?

[{prodId:'10',qnty:'12',total:'1200'}, 
{prodId:'11',qnty:'2',total:'10'}, 
{prodId:'4',qnty:'10',total:'50'}]

i have the following class 我有以下课程

public class ListItem{
    public int prodID {get;set;}
    public int qnty {get;set;}
    public decimal total {get;set;}
}

the above json array will be sent from ajax call to an action method. 上面的json数组将从ajax调用发送到action方法。 In the action method i need to build a List<ListItem> collection from the json array. 在动作方法中,我需要从json数组构建一个List<ListItem>集合。 How do i do this? 我该怎么做呢?

UPDATES here is the controller 这里的更新是控制器

public class ShoppingCartController : Controller
{

    public JsonResult AddToShoppingCart(string  jsonString)
    {
        int carId = 0;

        string[] str=  jsonString.Split(',');

        for (int i = 0; i < str.Length; i++)
        {
            if (str[i] == "cartId")
            {
                string tmp = str[i].Split(':').LastOrDefault();
                carId = int.Parse(tmp);

                if (carId == -1)
                {
                    //create new cart
                }
                else { 

                }
            }
        }
    }

Here is the ajax: 这是ajax:

  $('#addToCartForm #add').on('click', function () {
                   $.ajax({
                        url: 'ShoppingCart/AddToShoppingCart',
                        method: 'post',
                        data: JSON.stringify(item),
                        dataType: 'json',
                        success: function (data) {

                        },
                        error: function (jqXHR, textStatus, errorThrown) {

                        }
                    });
                });

Change you POST method to 将您的POST方法更改为

public JsonResult AddToShoppingCart(List<ListItem> model)

and the script to 和脚本

 $('#addToCartForm #add').on('click', function () {
     $.ajax({
         url: '@Url.Action("AddToShoppingCart", "ShoppingCart")', // don't hard code
         method: 'post',
         data: JSON.stringify({ 'model': item }),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         success: function (data) {
         },
         error: function (jqXHR, textStatus, errorThrown) {
         }
     });
});

assuming item is the javascript array your have shown. 假设item是您显示的javascript数组。 The DefaultModelBinder will correctly bind the collection DefaultModelBinder将正确绑定集合

you can De-serialize you string variable to your object List 您可以将字符串变量反序列化为对象列表

by Code 按代码

var obj = jsonString.Deserialize<List<ListItem>>();

public static T Deserialize<T>(this string json)
        {
            T returnValue;
            using (var memoryStream = new MemoryStream())
            {
                var settings = new DataContractJsonSerializerSettings
                {
                    DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("yyyy-MM-dd HH:mm:ssZ") 

                };
                byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
                memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
                memoryStream.Seek(0, SeekOrigin.Begin);
                using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null))
                {
                    var serializer = new DataContractJsonSerializer(typeof(T),settings);
                    returnValue = (T)serializer.ReadObject(jsonReader);
                }
            }
            return returnValue;
        }

Deserialize JSON into C# dynamic object? 将JSON反序列化为C#动态对象?

You can use ToObject method of JArray class when the json structure same to C# class structure. 当json结构与C#类结构相同时,可以使用JArray类的ToObject方法。 like this: 像这样:

List<ListItem> result = JArray.ToObject<List<ListItem>>();

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM