简体   繁体   中英

C# JSON file into list

In my C# + WPF + .NET 4.5 code, suppose I have defined a Player class in the following manner:

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):

{
  "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:

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.

PM> Install-Package Newtonsoft.Json -Version 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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