9

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);
  }
}

2 Answers 2

35

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));
Sign up to request clarification or add additional context in comments.

3 Comments

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MyApp.Player]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
@baytas First, use the serialization code File.WriteAllText... and compare the result with yours. Most probably you are not forming a correct json array. (For ex, the json in your question misses a comma between objects.)
Just for the sake of completion: The objects must be enclosed in [ ] so it's an array, and the objects must be separated by comas [{"firstName":"value1"},{"firstName":"value1"}]
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.