JsonConvert.DeserializeObject System.NullReferenceException

时间:2020-06-22 11:34:33

标签: c# class

我正在尝试将动态JSON从站点下载到var Vjson。 反序列化它并向控制台显示一些内容。 我不知道我在做什么错。我收到NullReferenceException错误,但是我确定有数据。


        {
                var client = new WebClient();
                var Vjson = client.DownloadString(Some URL);
                dynamic Post = JsonConvert.DeserializeObject( Vjson);
                foreach (var item in Post.Match)  //loop through class    //Post Match error System.NullReferenceException
            {
                Console.WriteLine("{0} {1} \n", item.ip_str, item.port);
            }

班级是

   class Post
 
    {

        public class Location
        {

            public string city { get; set; }
            ....
            public string country_name { get; set; }

        }

        public class Options
        {

        }

        public class Scodder
        {
            public string crawler { get; set; }
            ...
            public Options options { get; set; }
        }

        public class AngularJS
        {
            public IList<string> categories { get; set; }
        }

        public class Components
        {
            public AngularJS AngularJS { get; set; }
        }

        public class Http
        {
            public int? robots_hash { get; set; }
            ....
            public string waf { get; set; }
        }
        public class Match                      // Post.Match
        {
            ...
            public int port { get; set; }        //---- data i try to extract 
            ....
            public string ip_str { get; set; }   //---- data i try to extract 
            ...
        }
        public IList<Match> matches { get; set; }
        public int total { get; set; }
    }

我在做什么错了?

3 个答案:

答案 0 :(得分:0)

尝试

public List<Match> matches { get; set; }

代替

public IList<Match> matches { get; set; }

foreach (var item in Post.Match)  

但是您没有这样的集合,您有集合public IList<Match> matches { get; set; }

改为尝试

foreach (var item in Post.matches)  

为什么不能使用反序列化的通用版本?

JsonConvert.DeserializeObject<Post>(Vjson)

答案 1 :(得分:0)

尝试

a.setText();

代替

foreach (var item in Post.matches)

答案 2 :(得分:0)

由于未提供json字符串,因此无需任何调试 我可以想到2种变化

在Post类中添加无参数的公共构造函数

class Post
{
    public Post()
    {
    }
}

然后像下面这样反序列化json字符串

var x1 = JsonConvert.DeserializeObject<Post>(Vjson);
相关问题