首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSON对象Null

JSON对象Null
EN

Stack Overflow用户
提问于 2015-06-05 06:58:12
回答 1查看 96关注 0票数 0

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

JSON档案:

代码语言:javascript
复制
"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”的结果,但在那之后,错误出现了'object未设置为对象的实例‘

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-05 07:12:32

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

代码语言:javascript
复制
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的构造函数中使用这些对象的默认值。

代码语言:javascript
复制
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();
        }
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30660233

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档