Deserializing
We will instal third party application called JSON.NET and we will need help of NuGet Package Manager to install it.
The steps:
- Right click on our application project in Solution Explorer > Manage NuGet packages.
- Under Browse > newtonsoft.json > Install
- The documentation available here: http://www.newtonsoft.com/json/help/html/SerializingJSON.htm
Back to Main class. We will create method to deserialized our JSON.
First, add using namespace.
using Newtonsoft.Json;
Then, we add function to derserialized JSON.
public static List<Player> DeserializedPlayer(string fileName)
{
var players = new List<Player>();
var serializer = new JsonSerializer();
return players;
}
Now we add method to read from our file. First, we read from file as usual by
using (var reader = new StreamReader(fileName))
Then, we read that text using JsonReader.
using (var jsonReader = new JsonTextReader(reader))
After that, we define our json to convert into what kind of type.
using (var jsonReader = new JsonTextReader(reader))
{
serializer.Deserialize<List<Player>>(jsonReader);
}
Our full function should look like this.
public static List<Player> DeserializedPlayer(string fileName)
{
var players = new List<Player>();
var serializer = new JsonSerializer();
using (var reader = new StreamReader(fileName))
using (var jsonReader = new JsonTextReader(reader))
{
players = serializer.Deserialize<List<Player>>(jsonReader);
}
return players;
}
Now, back to our Main field. We will call the function.
fileName = Path.Combine(directory.FullName, "players.json");
var players = DeserializedPlayer(fileName);
foreach (var player in players)
Console.WriteLine(player.second_name);