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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With