JSON列表反序列化后如何操作对象

How to manipulate objects after JSON list deserialization

我正在尝试使用 JSON 文件来存储 Class,但我在反序列化过程中遇到了困难。

我正在使用以下命名空间:

using System.Text.Json.Serialization;

我有一个非常简单的 class,由 2 个属性组成:

public EnumOfType Type { get; set; }
public double Price { get; set; }

我有 4 个 classe 存储在列表中。退出应用程序时,此列表保存在 JSON 文件中。

string jsonString;
jsonString = JsonSerializer.Serialize(myListOfInstances);
File.WriteAllText(FileName, jsonString);

打开应用程序时,我希望加载 JSON 文件以重新创建实例。 我正在使用以下方法,显然效果很好。

string jsonString = File.ReadAllText(FileName);
myListOfInstances = JsonSerializer.Deserialize<List<MyClass>>(jsonString);

到目前为止一切顺利。当我检查列表的内容时,它被正确填充并且我的 4 个实例在那里。 但是...如何使用它们?

在 JSON 之前,我创建了每个实例(例如:)

MyClass FirstInstance = New MyClass();
FirstInstance.Type = EnumOfType.Type1;
FirstInstance.Price = 100.46;

然后我可以轻松地操作它,只需调用 FirstInstance。

myWindow.Label1.Content = FirstInstance.Price.ToString("C");
FirstInstance.Method1...

既然实例在我的列表中,我不知道如何单独操作它们,因为我不知道如何调用它们。

这对大多数人来说可能是显而易见的,但我仍在学习过程中。

感谢您的帮助,

很棒

根据您将 JSON 文件加载到程序中的方式,您的变量 myListOfInstances 似乎已经包含所有四个 MyClass 对象。此时,您可以使用 List 访问器(或者 Linq,如果你想花哨的话)并执行以下操作:

myListOfInstances[0] //Gives you the first item in the list accessed by index
myListOfInstances.First() //Gives you the first item in the list (using linq)

foreach(var item in myListOfInstances) {
    // this will iterate through all four items in the list storing each instance in 
    //the 'item' variable
}

等...

编辑:来自我下面的评论。如果需要直接访问列表中的值,可以使用 linq 和 'Where' 方法在列表中搜索特定条件。语法是这样的:

myListOfInstances.Where(x => x.Property == SomePropertyToMatch)