JSON对象空

时间:2015-06-05 06:58:12

标签: c# json json-deserialization

我成功反序列化JSON文件并且我得到了结果但是在结果结束后我得到'对象未设置为对象的实例'错误

JSON文件:

"radiant_team": {
          "team_name": "EHOME",
          "team_id": 4,
          "team_logo": 52122954231169668,
          "complete": true
        },
        "dire_team": {
          "team_name": "Team Secret",
          "team_id": 1838315,
          "team_logo": 543025270456493033,
          "complete": true

public partial class LiveLeagues
{
    public LiveGames Result { get; set; }
}
public class LiveGames
{
    public List<GameStats> games { get; set; }
    public int status { get; set; }
}
 public class GameStats
        {
            public List<BasePlayer> players { get; set; }
            public RadiantTeam radiant_team { get; set; }
            public DireTeam dire_team { get; set; }
        }

public class DireTeam
    {
        public string team_name { get; set; }
        public int team_id { get; set; }
        public object team_logo { get; set; }
        public bool complete { get; set; }
    }

public class RadiantTeam
    {
        public string team_name { get; set; }
        public int team_id { get; set; }
        public object team_logo { get; set; }
        public bool complete { get; set; }
    }

LiveLeagues.LiveLeagues liveGames = JsonConvert.DeserializeObject<LiveLeagues.LiveLeagues>(response.Content.ReadAsStringAsync().Result);

    foreach (var leagues in liveGames.Result.games)
        {
           MessageBox.Show(leagues.dire_team.team_id.ToString());
           MessageBox.Show(leagues.radiant_team.team_id.ToString());  
        }

我尝试迭代JSON并测试值是否会显示。我在MessageBox.Show上测试了它,我得到了结果“EHOME”和“Team Secret”,但之后错误出现'对象未设置为对象的实例

1 个答案:

答案 0 :(得分:1)

当json允许没有dire_team和/或radiant_team属性的游戏时,你应该进行空检查以确保它们在那里:

foreach (var leagues in liveGames.Result.games){ 
  if(leagues.dire_team != null)
    MessageBox.Show(leagues.dire_team.team_id.ToString());
  else
    MessageBox.Show("no dire team for this game");

  if(leagues.radiant_team != null)      
     MessageBox.Show(leagues.radiant_team.team_id.ToString());  
  else
    MessageBox.Show("no radiant team for this game");
}

或者您可以尝试在GameStats的构造函数中使用这些对象的默认值。

public class GameStats
    {
        public List<BasePlayer> players { get; set; }
        public RadiantTeam radiant_team { get; set; }
        public DireTeam dire_team { get; set; }

        public GameStats(){
          dire_team = new DireTeam();
          radiant_team = new RadiantTeam();
        }
    }