简体   繁体   中英

Json.Net Deserialize complex object

I have issue with deserialize JSON for next classes:

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

Result for Team object is always TeamId:0 and Name:null. DataContractJsonSerializer working for this example good, but Json.Net no. why? what I need change in my code, because I must to use Json.Net in my program?

This work well :

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

I prefer this Player Class

public class Player
{
    public Player()
    {
    } 

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

hope it helps

Still no. I can't reproduce the issue.

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

Prints:

3, 20 - ABC

4, 21 - ABCD

Perhaps you use some old version of Newtonsoft.Json?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM