jamheadart
jamheadart

Reputation: 5343

Why is JsonConvert.Deserialize() not parsing to the object it was serialised from?

I'm just exploring NewtonSoft - Why doesn't this work?

var x = JsonConvert.SerializeObject(MethodThatProducesGameInstance());
var y = JsonConvert.DeserializeObject(x);
Game g = (Game)y; // Error here

I can't serialize a Game object to a string and then deserialize the string back to a Game object - I thought that was the whole point of converting to and from Json? What am I missing?

My Game object is like so:

public class Game
{
    public Game()
    {
        Moves = new HashSet<Move>();
        GameHasPlayers = new HashSet<GameHasPlayer>();
    }

    public int Id { get; set; }

    public DateTime DateCreated { get; set; }

    [StringLength(1024)]
    public string Comment { get; set; }

    public virtual ICollection<Move> Moves { get; set; }

    public virtual ICollection<GameHasPlayer> GameHasPlayers { get; set; }
}

and the JSON produced from it into var x is like this:

"{\"Id\":3,\"DateCreated\":\"2019-11-13T14:31:54.303\",\"Comment\":\"First test game\",\"Moves\":[],\"GameHasPlayers\":[]}"

Upvotes: 0

Views: 41

Answers (1)

Klaycon
Klaycon

Reputation: 11080

Calling JsonConvert.DeserializeObject(x); with no generic type parameter will just deserialize it to the Object base class, which cannot be cast to a class deriving from it since it wasn't created as one.

Instead, pass the method a type parameter like this: JsonConvert.DeserializeObject<Game>(x); to explicitly tell the deserializer to create an instance of Game.

Upvotes: 2

Related Questions