我無法將json字符串反序列化爲對象。我有一個類似的實例可以很好地處理不同的類,但是我似乎無法使這個工作正常。這裏是這個類:Json DeserializeObject異常:「引用未設置爲對象的實例」
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中,那麼它應該被忽略,對吧?
你的json對象有STASK,你在代碼中指定了Stasks(jsonresponse [「Stasks」])。這可能是一個問題。 – lintmouse
此外,不是手動迭代數據,而是使用Json.net – Gusman
反序列化所有數據,拋出異常的行號將非常有幫助。其他然後大小寫不匹配@dustmouse發現,我沒有看到任何有關 –