Json.Net反序列化复杂对象

时间:2016-03-06 14:26:39

标签: c# .net json json.net

我遇到了针对下一个类反序列化JSON的问题:

public class Players:List<Player>
{
}

public class Player
{
    public Player()
    {
       PlayerTeam = new Team();
    } 

    public int PlayerId { get; set; }
    public Team PlayerTeam { get; set; } 
}

public class Team
{
    public int TeamId { get; set; }
    public string Name { get; set; }
}

Team对象的结果始终是TeamId:0和Name:null。 DataContractJsonSerializer为这个例子工作很好,但是Json.Net没有。为什么?我的代码需要改变什么,因为我必须在我的程序中使用Json.Net?

2 个答案:

答案 0 :(得分:1)

这项工作做得很好:

 static void Main(string[] args)
        {
            Player player = new Player
            {
                PlayerTeam = new Team { Name ="ABC", TeamId= 20 }, PlayerId = 3
            };


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

            Console.WriteLine(json);

            Player player_Des = JsonConvert.DeserializeObject<Player>(json);

            Console.WriteLine(player_Des.PlayerTeam.Name);

            Console.ReadLine();
        }

我更喜欢这个玩家类

public class Player
{
    public Player()
    {
    } 

    public int PlayerId { get; set; }
    public Team PlayerTeam { get; set; } 
}

希望有所帮助

答案 1 :(得分:1)

仍然没有。我无法重现这个问题。

public class Players : List<Player>
{
}

public class Player
{
    public Player()
    {
        PlayerTeam = new Team();
    }

    public int PlayerId { get; set; }
    public Team PlayerTeam { get; set; }
}

public class Team
{
    public int TeamId { get; set; }
    public string Name { get; set; }
}

...

var json = "[{ \"PlayerId\": 3, \"PlayerTeam\": { \"TeamId\": 20, \"Name\": \"ABC\" } },{ \"PlayerId\": 4, \"PlayerTeam\": { \"TeamId\": 21, \"Name\": \"ABCD\" } }]";
var players = JsonConvert.DeserializeObject<Players>(json);

foreach (var player in players)
{
    Console.WriteLine($"{player.PlayerId}, {player.PlayerTeam.TeamId} - {player.PlayerTeam.Name}");
}

打印:

  

3,20 - ABC

     

4,21 - ABCD

也许您使用的是旧版本的Newtonsoft.Json?