因此,這裏我有JsonResult jr
,它看起來像這樣(輸出是單行,我在此格式化):在將部分json轉換爲c#對象時發生了類型'Newtonsoft.Json.JsonReaderException'的第一次機會異常
string jr = {"Results":
[
{"Code":"DEMO",
"Id":"1285",
"Office":"9881",
"Customers":
[
2713,
94204
],
"Account":196,
"Appointments":
[
14,
58
],
"Role":0,
"UserName":"demo",
"UserId":3669,
"FirstName":"Peter",
"LastName":"Pan",
"Phones":
[
"(888) 888-8888"
],
"Fax":null,
"Email":"[email protected]",
"SMS":null,
"RecordStatus":"1"},
{"Code":"DEMO",
"Id":"9292",
"Office":"9881",
"Customers":
[
13,
904
],
"Account":196,
"Appointments":
[
14,
58
],
"Role":0,
"UserName":"berry",
"UserId":302,
"FirstName":"Jimmy",
"LastName":"White",
"Phones":
[
"(888) 888-8888"
],
"Email":"[email protected]",
"SMS":null,
"RecordStatus":"1"}
],
"TotalResults":2,
"MilliSeconds":4}
這裏是我的對象User
:
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Id { get; set; }
public string Office { get; set; }
public string Email { get; set; }
public string Code { get; set; }
}
我試圖用反序列化JSON的部分片段與JSON映射到我的對象: http://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm
我跟着這個例子,但是我得到了一個錯誤:Newtonsoft.Json.dll異常類型'Newtonsoft.Json.JsonReaderException'的第一次機會異常發生在Newtonsoft.Json.dll。
很多人在線說它是由壞json引起的。我檢查了我自己,沒有發現任何錯誤。下面是我的代碼:
JObject response = JObject.Parse(jr);
IList<JToken> results = response["Results"].Children().ToList();
IList<User> searchResults = new List<User>();
foreach(JToken result in results)
{
System.Diagnostics.Debug.WriteLine(result); //just to check my json data.
User searchResult = JsonConvert.DeserializeObject<User>(results.ToString()); //get exception on this line.
searchResults.Add(searchResult);
}
第一result
輸出看起來是這樣的:
{
"Code":"DEMO",
"Id":"1285",
"Office":"9881",
"Customers":
[
2713,
94204
],
"Account":196,
"Appointments":
[
14,
58
],
"Role":0,
"UserName":"demo",
"UserId":3669,
"FirstName":"Peter",
"LastName":"Pan",
"Phones":
[
"(888) 888-8888"
],
"Fax":null,
"Email":"[email protected]",
"SMS":null,
"RecordStatus":"1"
}
不知道爲什麼這發生異常時,不知道如何解決它..
您檢查了Json.Net併爲您的手機值自定義序列? – doogle
不是。我是c#的新手,不太確定你的意思是什麼。 –
http://www.newtonsoft.com/json是.Net的前往JSON庫,它可以做你想做的事但你必須向User類添加一些屬性,以便序列化程序知道哪些字段到達哪裏。 – doogle