将列表序列化/反序列化为JSON

时间:2018-06-14 13:35:15

标签: c# json asp.net-core

我正在尝试在我拥有的两个项目中序列化/反序列化对象列表。这是我正在使用的课程:

public class Stock
{
    public string Bin { get; set; }
    public string Article { get; set; }
    public int Quantity { get; set; }
}

我序列化的部分:

var msg = JsonConvert.SerializeObject(result.Select(k => new Stock() { Article = article, Bin = k.Bin, Quantity = k.Quantity }));

我反序列化的部分:

var stocks = JsonConvert.DeserializeObject<IEnumerable<Stock>>(data);

这是我得到的例外:

ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.IEnumerable`1[DTOs.Stock].

这是错误页面上显示的数据:

[{"Bin":"MJ11906","Article":"148400MU_","Quantity":50},{"Bin":"ME04307","Article":"148400MU_","Quantity":56},{"Bin":"MD08301","Article":"148400MU_","Quantity":66},{"Bin":"MG12303","Article":"148400MU_","Quantity":70},{"Bin":"ME04402","Article":"148400MU_","Quantity":72},{"Bin":"ME12402","Article":"148400MU_","Quantity":72}]

我找不到我做错了什么,我试图对List和Ienumerable进行序列化/反序列化,但结果是一样的。似乎找不到任何谷歌搜索结果......

1 个答案:

答案 0 :(得分:1)

我刚刚使用VS2017(Community Edition)创建了一个.NET Core 2.0控制台应用程序。代码如下:

using System;
using System.Collections.Generic;

using Newtonsoft.Json;

namespace JsonDemo
{
    public class Stock
    {
        public string Bin { get; set; }
        public string Article { get; set; }
        public int Quantity { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string json = @"[{""Bin"":""MJ11906"",""Article"":""148400MU_"",""Quantity"":50},{""Bin"":""ME04307"",""Article"":""148400MU_"",""Quantity"":56},{""Bin"":""MD08301"",""Article"":""148400MU_"",""Quantity"":66},{""Bin"":""MG12303"",""Article"":""148400MU_"",""Quantity"":70},{""Bin"":""ME04402"",""Article"":""148400MU_"",""Quantity"":72},{""Bin"":""ME12402"",""Article"":""148400MU_"",""Quantity"":72}]";

            var stocks = JsonConvert.DeserializeObject<IEnumerable<Stock>>(json);
            var stocks2 = JsonConvert.DeserializeObject<IList<Stock>>(json);
            var stocks3 = JsonConvert.DeserializeObject<List<Stock>>(json);
            var stocks4 = JsonConvert.DeserializeObject<Stock[]>(json);

            string json2 = JsonConvert.SerializeObject(stocks);

            stocks = JsonConvert.DeserializeObject<IEnumerable<Stock>>(json);
            stocks2 = JsonConvert.DeserializeObject<IList<Stock>>(json);
            stocks3 = JsonConvert.DeserializeObject<List<Stock>>(json);
            stocks4 = JsonConvert.DeserializeObject<Stock[]>(json);

            Console.WriteLine("Press any key to continue");
            Console.Read();
        }
    }
}

没有抛出异常。我尝试过使用nuget包Newtonsoft.Json的9.0.1,10.0.1和11.0.2版本,一切都按预期工作。

您是否尝试过使用更新版本的Newtonsoft.Json?