尝试检索json数据时,对象引用未设置为对象的实例

时间:2014-01-06 10:32:05

标签: c# json

我正在尝试从以下网址https://www.gov.uk/api/foreign-travel-advice.json

获取数据

我使用http://json2csharp.com/来提取类,但我无法获取我之后的数据。

任何比我更有经验的人都可以看看,让我知道我哪里出错了。

这是抛出null referance的代码

var data = (from j in o["countries"].Children()
                        select new Country
                        {
                                Id      = (string)j["id"],
                                WebUrl  = (string)j["name"]
                        });

完整代码

namespace Web.Domain.FCO.Countries
{
    public class Details
    {
        public string Description { get; set; }
        public object ShortDescription { get; set; }
        public string Type { get; set; }
    }

    public class ContentWithTag
    {
        public string Id { get; set; }
        public string WebUrl { get; set; }
    }

    public class Details2
    {
        public string Description { get; set; }
        public object ShortDescription { get; set; }
        public string Type { get; set; }
    }

    public class ContentWithTag2
    {
        public string Id { get; set; }
        public string WebUrl { get; set; }
    }

    public class Parent
    {
        public string Id { get; set; }
        public object WebUrl { get; set; }
        public string Title { get; set; }
        public Details2 Details { get; set; }
        public ContentWithTag2 ContentWithTag { get; set; }
        public object parent { get; set; }
    }

    public class Tag
    {
        public string Id { get; set; }
        public object WebUrl { get; set; }
        public string Title { get; set; }
        public Details Details { get; set; }
        public ContentWithTag ContentWithTag { get; set; }
        public Parent Parent { get; set; }
    }

    public class Related
    {
        public string Id { get; set; }
        public string WebUrl { get; set; }
        public string Title { get; set; }
        public string Format { get; set; }
        public string UpdatedAt { get; set; }
        public string Group { get; set; }
    }

    public class Country
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Identifier { get; set; }
        public string WebUrl { get; set; }
        public string UpdatedAt { get; set; }
        public string ChangeDescription { get; set; }
        public List<object> Synonyms { get; set; }
    }

    public class Details3
    {
        public string NeedId { get; set; }
        public bool BusinessProposition { get; set; }
        public string Description { get; set; }
        public string Language { get; set; }
        public bool NeedExtendedFont { get; set; }
        public List<Country> Countries { get; set; }
    }

    public class ResponseInfo
    {
        public string Status { get; set; }
    }

    public class FcoFullDetails
    {
        public string Id { get; set; }
        public string WebUrl { get; set; }
        public string Title { get; set; }
        public string Format { get; set; }
        public string UpdatedAt { get; set; }
        public List<Tag> Tags { get; set; }
        public List<Related> Related { get; set; }
        public Details3 Details { get; set; }
        public List<object> RelatedExternalLinks { get; set; }
        public ResponseInfo ResponseInfo { get; set; }
    }

    public class IdAndUrl
    {
        public string Id { get; set; }
        public string WebUrl { get; set; } 
    }

    public class DisplayFcoCountryList : IDisplayFcoCountryList
    {
        public IEnumerable<Country> ListOfCountries()
        {
            var doc = FcoCountriesAdvice.GetFcoCountryLinks().Result;
           // var jd = new [] {JsonConvert.DeserializeObject(doc)};
            var jd = JsonConvert.DeserializeObject(doc);
            JObject o = JObject.Parse(jd.ToString());

            //var data = (from j in o["countries"]
                        var data = (from j in o["countries"].Children()
                        select new Country
                        {
                                Id      = (string)j["id"],
                                WebUrl  = (string)j["name"]
                        });
            return data;
        }
    }
    public static class FcoCountriesAdvice
    {
        private static readonly string Key = ConfigurationManager.AppSettings["FCO_AdviceURL"];

        public static async Task<string> GetFcoCountryLinks()
        {
            using (var ta = new HttpClient())
            {
                const string cacheDataTravelAdvice = "FCOCountryLinks";

                ObjectCache travelCache = MemoryCache.Default;
                var objectInCache = travelCache.Get(cacheDataTravelAdvice) as string;

                if (objectInCache != null)
                {
                    return objectInCache;
                }

                var url = await ta.GetStringAsync(string.Format("{0}", Key)).ConfigureAwait(false);

                var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(15) };

                travelCache.Add(cacheDataTravelAdvice, url, policy);

                return url;
            }
        }
    }
}

3 个答案:

答案 0 :(得分:0)

创建linq语句时的nullref异常很可能意味着部分:o["countries"].Children()返回NULL,因此无法迭代。尝试使用一些简单的语句进行调试时会发生什么:

  

Console.WriteLine(O [ “国家”]);

     

Console.WriteLine(O [ “国家”]儿童());

     

Console.WriteLine(问题o [ “国家”]儿童()计数());

答案 1 :(得分:0)

尝试使用像JSON.net这样的json反序列化器。这将为您完成所有json-c#转换:

    //make request using the HttpClient class
    var client = new HttpClient{BaseAddress = new Uri("https://www.gov.uk/api/")};
    var response = client.GetAsync("foreign-travel-advice.json").Result;

    //use Json.Net to convert json to c# classes using generics
    var content = JsonConvert.DeserializeObject<RootObject>    (response.Content.ReadAsStringAsync().Result);

答案 2 :(得分:0)

Alessio回答修复了问题,在访问了他提供的链接之后,我发现我本应该使用var data =(来自j [o“]”[“countries”]。儿童()不是var data = (来自j in o [“countries”]。儿童()。问题现已解决。