方法JsonConvert.DeserializeObject将id转换为零

时间:2015-06-28 09:58:53

标签: c# json serialization

我有一个字符串:

string model = "{\"Game\":{\"GameId\":1,\"Board\":[0,0,0,0,0,0,0,0,0],\"User1Id\":1,\"User2Id\":2,\"UserIdTurn\":1,\"WinnerId\":0,\"IsGameOver\":false},\"User\":{\"UserId\":1,\"UserName\":\"a\",\"Password\":\"a\",\"Password2\":\"a\",\"Games\":[]}}" 

当我使用此代码时:

GameModel myModel = JsonConvert.DeserializeObject<GameModel>(model);

它工作得很好但只有一个问题 - 它将我的游戏和用户ID改为零。为什么会这样,我该如何解决? 我顺便写一下c#。

这些是我的课程:

        public class GameModel
    {

        public Game Game { get; set; }

        public User User { get; set; }

    }

public class Game
    {

        public Game()
        {
            Board = new SquareState[9];                     
        }

        public Game(int user1Id)
        {
            Board = new SquareState[9];
            User1Id = user1Id;
            UserIdTurn = user1Id;
        }
        public int GameId { get; private set; }

        public SquareState[] Board { get; set; }

        [Required]
        public int User1Id { get; set; }

        public int User2Id { get; set; }

        public int UserIdTurn { get; set; }


        public int WinnerId { get; set; }

        public bool IsGameOver { get; set; }

    }

    public class User
    {
        public User()
        {
            Games = new List<Game>();
        }
        public int UserId { get; private set; }

        [Required]
        [Display(Name = "User Name:")]
        public string UserName { get; set; }


        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Required]
        [Display(Name = "re-enter Password")]
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Passwords not match")]
        public string Password2 { get; set; }

        public List<Game> Games { get; set; }
    }

1 个答案:

答案 0 :(得分:1)

您的课程在没有GameIdUserId的情况下进行反序列化的原因是因为您将这两者的setter方法设置为private范围。

反序列化程序无法访问它们,因为它们不可用。

尝试将它们公开并再次运行它们将按预期反序列化:

public class Game
{
    ...
    public int GameId { get; set; }
    ...
}

public class User
{
    ...
    public int UserId { get; set; }
    ...
}