Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# JSON file into list

Tags:

json

c#

json.net

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

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);
  }
}
like image 879
mbaytas Avatar asked May 07 '13 09:05

mbaytas


2 Answers

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));
like image 169
I4V Avatar answered Sep 21 '22 07:09

I4V


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);
like image 36
R M Shahidul Islam Shahed Avatar answered Sep 25 '22 07:09

R M Shahidul Islam Shahed