C# Newtonsoft JSON Serialize and Deserialize of Objects

So after abit of headache. I figured out how to serialize nested objects and deserialize them. This is especially useful for doing Android Development with C#.

So for starters!

Here are the Objects/Models

public class Game

      public class Game
        public Player currentPlayer;

        public Player player1;
        public Player player2;
        public Die die;
        public int currentRound;
        public bool canRoll;
        public bool gameOver;
        public Player winner;

public class Player

    public class Player
        public string Name { get; set; }
        public int Score { get; set; }
        public bool FinalRollComplete { get; set; }

So the [JsonObject(MemberSerialization.OptIn)] is optional when everything is public. However if I had a protected class I would need it and the JsonProperty in order to store it in my json string.

 public class Die
        public int currentValue;

Ok so now you know the setup, lets talk about the actual serialize and deserialize.


string json = JsonConvert.SerializeObject(this.Game, Formatting.Indented);


 Game = JsonConvert.DeserializeObject<Game>(json);

So this also requires you install the NuGet package for Newtonsoft.Json and add the

using Newtonsoft.Json;

at the top