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; }
}

团队对象的结果始终为 TeamId:0和名称:空。DataContractJsonSerializer 适用于此示例很好,但 Json.Net 没有。为什么?我需要在代码中更改什么,因为我必须在程序中使用 Json.Net?

这很好用:

 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; } 
}

希望对您有所帮助

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

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?

相关内容

  • 没有找到相关文章

最新更新