简体   繁体   English

C#JSON文件放入列表

[英]C# JSON file into list

In my C# + WPF + .NET 4.5 code, suppose I have defined a Player class in the following manner: 在我的C# + WPF + .NET 4.5代码中,假设我以以下方式定义了Player类:

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

And I have a myobjects.json file in which I managed to write (using JSON.NET ) a serialized collection of these objects (first two shown below): 我有一个myobjects.json文件,在其中我设法编写(使用JSON.NET )这些对象的序列化集合(如下所示的前两个):

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

What I would like to do is to read the file, and deserialize these objects and populate a List of Player s: 我想做的是读取文件,反序列化这些对象并填充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);
  }
}

No need to read item by item. 无需逐项阅读。

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

You can use this code to write your player list to file 您可以使用此代码将播放器列表写入文件

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

In C# .Net core console application: First, install Newtonsoft from NuGet by the following command. 在C#.Net核心控制台应用程序中:首先,通过以下命令从NuGet安装Newtonsoft。

PM> Install-Package Newtonsoft.Json -Version 12.0.2 PM>安装软件包Newtonsoft.Json-版本12.0.2

    string filePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\")) + @"Data\Country.json";
    string _countryJson = File.ReadAllText(filePath);
    var _country = JsonConvert.DeserializeObject<List<Country>>(_countryJson);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM