0

I have a list of Team that I am trying to deserialise.

class Team  
{
    public string TeamName {get; set;};
    private List<FootballPlayer> _fPlayers = new List<FootballPlayer>();
    public List<FootballPlayer> FPlayers
    {
        get => _fPlaters;
    }
}

class FootballPlayer
{
    private Team _team;

    public string Name { get; set; }
    public Team Team 
    {
        get => _team;
    }

    [JsonConstructor]
    public FootballPlayer(Team team)
    {
        _team = team;
    }
}

I have the following JSON settings:

JsonSerializerSettings serializerSettings = new JsonSerializerSettings()
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects,
    Formatting = Formatting.Indented
};

When I look at the serialised output, it appears correct, and the references between nodes are properly represented.

  {
      "$id": "1",
      "TeamName": "Test",
      "FPlayers": [
      {
        "$id": "2",
        "Team": {
          "$ref": "1"
        },
        "Name": "Leo Messi"
      }
    ]
  }

When the data is deserialised, the property "Team" in the player "Leo Messi" is null.

How can I deserialise this JSON in such a way that the property "Team" of "Leo Messi" is not null?

JsonConvert.DeserializeObject<List<Team>>(JsonString, serializerSettings);
Giovanni
  • 29
  • 7
  • this json is an object not an array, why you use `List`? – Mohammed Sajid May 21 '20 at 18:11
  • @Sajid I trimmed the json for readability – Giovanni May 21 '20 at 18:13
  • `PreserveReferencesHandling` is documented to not work with parameterized constructors, see [Newtonsoft.Json issue with deserialising relational model](https://stackoverflow.com/a/61212033/3744182), of which I believe this is a duplicate. – dbc May 21 '20 at 22:52
  • @dbc thanks you! If a want deserialise a field that is readonly how can i do? – Giovanni May 22 '20 at 22:40

0 Answers0