如何将对象数据的JSON数组分配给T的适当列表

时间:2018-09-25 05:31:13

标签: c# asp.net-mvc dynamic

我有两种类型的SalesData和CollectionData。这两种类型是完全不同的类型。因此,当我将数据传递给前端时,我会创建动态数据类型,然后根据调用将数据传递给前端。

在接收数据时,我创建了json数据,它是对象数组。

现在我处于困境中,如何根据类型将传入数组分配给List或List。

这就是我所做的。

public ActionResult DownloadDataInExcel(List<object>data, int type)
        {
            if (type == (int)MyEnum.Sales)
            {
                var mycontacts = JsonConvert.DeserializeObject<List<SalesData>>(data.ToString());

                foreach (var item in mycontacts)
                {
                    System.Diagnostics.Debug.WriteLine($"{item.Name}-{item.City}-{item.Country}");
                }
            }else
            {
                var mycontacts = JsonConvert.DeserializeObject<List<CollectionData>>(data.ToString());

                foreach (var item in mycontacts)
                {
                    System.Diagnostics.Debug.WriteLine($"{item.Name}-{item.City}-{item.Country}");
                }
            }

            //to do: Convert data to Excel File

            throw new NotImplementedException();

        }

2 个答案:

答案 0 :(得分:1)

1)您需要一种通用方法来将传入的json反序列化为适当的List<>对象

public static List<T> DeserializeList<T>(string json)
{
    return JsonConvert.DeserializeObject<List<T>>(json);
}

2)在这里,我创建一个控制台应用程序供您演示。

class Program
{
    static void Main(string[] args)
    {
        string json1 = @"[{'Id1':'1','Name1':'Mike','Age1':43},{'Id1':'2','Name1':'Anna','Age1':56}]";
        string json2 = @"[{'Id2':'1','Name2':'Mike','Age2':43},{'Id2':'2','Name2':'Anna','Age2':56}]";

        //Pass json1 and deserialize into list of Sample1
        var sample1List = DeserializeList<Sample1>(json1);
        sample1List.ForEach(x => Console.WriteLine($"Id1: {x.Id1},  Name1: {x.Name1}, Age1: {x.Age1}"));

        Console.WriteLine("\n");

        //Pass json2 and deserialize into list of Sample2
        var sample2List = DeserializeList<Sample2>(json2);
        sample2List.ForEach(x => Console.WriteLine($"Id2: {x.Id2},  Name2: {x.Name2}, Age2: {x.Age2}"));

        Console.ReadLine();
    }

    public static List<T> DeserializeList<T>(string json)
    {
        return JsonConvert.DeserializeObject<List<T>>(json);
    }
}

class Sample1
{
    public string Id1 { get; set; }
    public string Name1 { get; set; }
    public int Age1 { get; set; }
}


class Sample2
{
    public string Id2 { get; set; }
    public string Name2 { get; set; }
    public int Age2 { get; set; }
}

输出:

enter image description here

答案 1 :(得分:0)

您可以使用try-catch

try
{
     var someresult = JsonConvert.DeserializeObject<Type1>(data.ToString());
     // data was Type1 indeed, deal with Type1
}
catch{} 
try
{
     var someresult = JsonConvert.DeserializeObject<Type2>(data.ToString());
     // data was Type2 indeed, deal with Type2
}
catch{}