Json DeserializeObject异常:“引用未设置为对象的实例”

时间:2016-02-29 14:09:36

标签: c# json json.net

我无法将json字符串反序列化为对象。我有一个类似的实例适用于不同的类,但我似乎无法让这个正常工作。这是班级:

    class Task
{
    public string ProviderID { get; set; }
    public string Id { get; set; }
    public string UserEmail { get; set; }
    public string Name { get; set; }
    public string Status { get; set; }
    public string CompleteBy { get; set; }
    public string CompleteAtLat { get; set; }
    public string CompleteAtLon { get; set; }
    public string PerformWithin { get; set; }
    public string AdditionalInfo { get; set; }
    public string UserCanReject { get; set; }
    public string StartTime { get; set; }
    public string CompleteTime { get; set; }
    public string ActualCompleteLat { get; set; }
    public string ActualCompleteLon { get; set; }
    public string UserNotes { get; set; }



    public static IList<Task> Get()
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url");
        req.Method = "GET";
        req.ContentType = "application/json";
        HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        using (StreamReader sr = new StreamReader(res.GetResponseStream()))
        {
            string text = sr.ReadToEnd();
            JObject jsonresponse = JObject.Parse(text);
            Console.WriteLine(jsonresponse.ToString());
            IList<JToken> results = jsonresponse["Stasks"].Children().ToList();
            IList<Task> tasks = new List<Task>();
            foreach (JToken result in results)
            {
                Task task = JsonConvert.DeserializeObject<Task>(result.ToString());
                tasks.Add(task);
            }
            return tasks;

        }
    }

这是我试图反序列化的Json字符串示例。

    {
   "STasks":[
      {
         "ProviderId":"xxxxx",
         "Id":"xxxxx",
         "UserEmail":"xxxxx",
         "Name":"test",
         "Status":"Completed",
         "CompleteBy":"2014-11-15T15:17:00.0000000Z",
         "CompleteAtLat":0,
         "CompleteAtLon":0,
         "PerformWithin":50,
         "AdditionalInfo":"trsgghghfhghh",
         "UserCanReject":true,
         "STaskActivities":[
            {
               "Instruction":"fsdgggdg",
               "OutcomeId":"00000000000000000000000000000000",
               "CompleteTime":"2014-11-14T15:19:37.0000000Z",
               "ActivityType":"Instruction"
            }
         ],
         "STaskHistories":[
            {
               "EventDate":"2014-11-14T15:18:27.2975697Z",
               "Status":"Draft"
            },
            {
               "EventDate":"2014-11-14T15:18:54.8263294Z",
               "Status":"Sent"
            },
            {
               "EventDate":"2014-11-14T15:19:37.7176027Z",
               "Status":"Accepted"
            },
            {
               "EventDate":"2014-11-14T15:19:49.0975573Z",
               "Status":"Completed"
            }
         ],
         "StartTime":"2014-11-14T15:19:37.0000000Z",
         "CompleteTime":"2014-11-14T15:19:47.0000000Z",
         "ActualCompleteLat":52.6091012845814,
         "ActualCompleteLon":4.75544677437253,
         "UserNotes":"Fyujvhfdkskbvdskbdvsbkdsvhkj"
      }
   ]
}

我找不到任何关于这种方法是如何工作的详细解释,所以也许我在这里遗漏了一些东西。如果我的课程中没有属性但它确实出现在Json中,那么它应该被忽略,对吗?

1 个答案:

答案 0 :(得分:0)

我认为你只是在解析错误的JSON树(双关语!)。

当我将JSON映射到类中时,反序列化按预期工作。试试这个:

顶级JSON映射:

public class STasksContainer
{
    public STask[] STasks{get;set;}
}

还为主数组元素添加此映射:

public class STask
{
    public string ProviderId {get;set;}
    public string Id{get;set;}
    public string UserEmail{get;set;}
    public string Name{get;set;}
    public string Status{get;set;}
    public string CompleteBy{get;set;}
    public double CompleteAtLat{get;set;}
    public double CompleteAtLon{get;set;}
    public int PerformWithin{get;set;}
    public string AdditionalInfo{get;set;}
    public bool UserCanReject{get;set;}
    public string StartTime{get;set;}
    public string CompleteTime{get;set;}
    public double ActualCompleteAtLat{get;set;}
    public double ActualCompleteAtLon{get;set;}
    public string UserNotes{get;set;}
    public STaskActivity[] STaskActivities{get;set;}
    public STaskHistory[] STaskHistories{get;set;}
}

最后,在STask中添加两个嵌套数组元素的映射:

public class STaskActivity
{
    public string Instruction{get;set;}
    public string OutcomeId{get;set;}
    public string CompleteTime{get;set;}
    public string ActivityType{get;set;}
} 

public class STaskHistory
{
    public string EventDate{get;set;}
    public string Status{get;set;}
}

您可以测试代码:

using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
    string text = sr.ReadToEnd();
    var sTaskRoot = JsonConvert.DeserializeObject<STasksContainer>(text);
}

HTH ...!