【问题标题】:Is there any possible way to deserialize a Json file made from a list of objects to a list of the same objects in c# and how can it be done? [duplicate]是否有任何可能的方法可以将由对象列表生成的 Json 文件反序列化为 c# 中相同对象的列表,以及如何完成? [复制]
【发布时间】:2026-01-25 18:45:02
【问题描述】:

我尝试了许多不同的代码来反序列化 Json_List 中的对象,但每次应该保存我的对象的列表即使在反序列化之后也会获得空值。顺便说一句,我正在使用 Newtonsoft.Json 命名空间。当我序列化对象时它工作得很好,但反序列化时它完全失败了。

public void Load(string fileName)
{

          //I found a way that works but its trivial and I think it can be done with a better code without using
         // an array and a loop 
            Curve[] arrCurves = new Curve[1024];
            JsonSerializer ser = new JsonSerializer { TypeNameHandling = TypeNameHandling.Auto };
            using (TextReader reader = File.OpenText(fileName))
            {
                _curves.Clear();
                //_curves.Add(ser.Deserialize(reader, typeof(Curve)) as Curve);
                //_curves.Add(ser.Deserialize(reader, typeof(List<Curve>)) as Curve);
                arrCurves = ser.Deserialize(reader, typeof(Curve[])) as Curve[];
                for (int i = 0; i < arrCurves.Length; i++)
                {
                    _curves.Add(arrCurves[i]);
                }
            }
} 

顺便说一句,代码可以工作,但我想知道我是否可以在没有循环的情况下做到这一点,而且“_curves”列表是只读列表

【问题讨论】:

标签: c# json.net json-deserialization jsonconvert


【解决方案1】:

这是给你的例子(在 Newtonsoft 中)

 public class Curve
{
    public int a { get; set; } = 3;
    public string b { get; set; }
    public Curve(int a, string b) { this.a = a; this.b = b; }
}
internal class Program
{
    public static void Main(string[] args)
    {
        List<Curve> curves = new List<Curve>()
        {
            new Curve(1,"x"), new Curve(3,"y")
        };
        var json = JsonConvert.SerializeObject(curves);
        Console.WriteLine(json);

        var restored = JsonConvert.DeserializeObject<List<Curve>>(json);

        foreach (var curve in restored) Console.WriteLine($"Curve: {curve.a}, {curve.b}");
        Console.ReadLine();
    }

控制台中的结果:

[{"a":1,"b":"x"},{"a":3,"b":"y"}] 曲线:1,x 曲线:3,y

因为我担心类的字段必须是公共的,序列化程序才能正常工作,所以先在你的代码中尝试一下吧。

【讨论】:

  • 您的答案显示了如何通过反序列化创建新的List&lt;Curve&gt;——但问题不在于如何做到这一点。问题是如何将曲线列表反序列化为 preexisting List&lt;Curve&gt; 而无需创建新列表。
  • @Mike 不,那是行不通的。我的代码中已经存在的列表在另一个方法和类中使用,所以我不需要创建另一个列表+我已经使用了循环并解决了问题,但我正在寻找不使用循环的代码。但是感谢您的努力 :)
  • 好吧,您可以使用“preexisting”和“newlist”列表并执行 preexisting = preexisting.Union(newlist) 编辑:根据您对元素的唯一性和顺序的期望,还有一些其他的更短且不需要文字循环的 linq 选项
最近更新 更多