C# C# Streams and Data Processing Serialization Deserializing with Json.NET

Syed Abbas
Syed Abbas
4,762 Points

Deserialization using Json

Hi I have followed along with the video for deserialization with Json but my screen comes out blank when I try to print the names of players. I am not sure whats wrong with it. Please someone help. I have the following code. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Newtonsoft.Json;

namespace file_input_output { class Program { static void Main(string[] args) {

        string currentDirectory = Directory.GetCurrentDirectory();
        DirectoryInfo directory = new DirectoryInfo(currentDirectory);

        var fileName = Path.Combine(directory.FullName,"players.json");
        var players = DeserialisePlayers(fileName);

        foreach (var player in players)
        {
            Console.WriteLine(player.first_name);
        }
    }


    public static List<Player> DeserialisePlayers (string fileName)
    {
        var players = new List<Player>();
        var serializer = new JsonSerializer();
        using (var reader = new StreamReader(fileName)) 
        using (var jsonReader = new JsonTextReader(reader))
        {
            serializer.Deserialize<List<Player>>(jsonReader);
        }
            return players;
    }
}

}

3 Answers

Daniel Jenkins
Daniel Jenkins
17,713 Points

Your list of players is declared as an empty list at the beginning of the DeserilasePlayers but never has any data assigned to it. Within your 'using' statements you are deserialising the json output by your jsonTextReader but not doing anything with it. Try assigning that output to the 'players' list. Hope that makes sense.

Pierre Gadea
Pierre Gadea
4,450 Points

Could just be a typo somewhere. Can you post what the instructions for the challenge say?

Keegan Usher
PRO
Keegan Usher
Pro Student 25,399 Points

I know this question is old but it might help some else. I still had my break point in the ReadSoccerResults method active so it kept the code from moving on to the DeserializePlayers method and in turn gave a blank cmd window. Once I removed that second breakpoint it worked.