gpt4 book ai didi

C# JSON 文件到列表

转载 作者:太空狗 更新时间:2023-10-29 22:08:13 25 4
gpt4 key购买 nike

在我的 C# + WPF + .NET 4.5 代码中,假设我定义了一个 Player 类以下方式:

public class Player {
public string FirstName;
public string LastName;
public List<int> Cells;
public string Level;
}

我有一个 myobjects.json 文件,我设法在其中编写(使用 JSON.NET )这些对象的序列化集合(前两个如下所示):

{
"FirstName": "Foo",
"LastName": "Fighter",
"Cells": [
1,
2,
3
],
"Level": "46"
}{
"FirstName": "Bar",
"LastName": "Baz",
"Cells": [
104,
127,
],
"Level": "D2"
}

我想做的是读取文件,反序列化这些对象并填充 PlayerList:

using (Stream fs = openDialog.OpenFile())
using (StreamReader sr = new StreamReader(fs))
using (JsonTextReader jr = new JsonTextReader(sr)) {
while (jr.Read()) {
/* Find player in file */
Player p = /* Deserialize */
PlayerList.Add(p);
}
}

最佳答案

无需逐条阅读。

string json = File.ReadAllText("myobjects.json");
var playerList = JsonConvert.DeserializeObject<List<Player>>(json);

您可以使用此代码将播放器列表写入文件

File.WriteAllText("myobjects.json", JsonConvert.SerializeObject(playerList));

关于C# JSON 文件到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16416138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com