[英]Issue deserializing json string
我正在使用 newtonsoft json 反序列化 json 字符串並將內容寫入數據表,遇到錯誤。 我可以使用 JavaScriptSerializer class 進行此操作,但不能使用 newtonsoft json。請指出我哪里做錯了。
請在下面找到 json 示例。
JSON:
[{
"Id": 1,
"FirstName": "Jason1",
"LastName": "Test1",
"Email": "123@automail.com",
"Eligible": true,
"InsertLogtime": "2022-02-21T00:51:59.917",
"Comment": null
},
{
"Id": 2,
"FirstName": "Jason2",
"LastName": "Test2",
"Email": "234@automail.com",
"Eligible": true,
"InsertLogtime": "2022-02-21T00:51:59.917",
"Comment": null
}
]
C#:
public class Profile
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public bool Eligible { get; set; }
public DateTime InsertLogtime { get; set; }
public object Comment { get; set; }
}
public class Root
{
public List<Profile> profile { get; set; }
}
var jstring = JsonConvert.DeserializeObject<Root>(profile);
//string profile has data in the sample specified
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(int)));
dt.Columns.Add(new DataColumn("FirstName", typeof(string)));
dt.Columns.Add(new DataColumn("LastName", typeof(string)));
DataRow dr = dt.NewRow();
for (int i = 0; i < jstring.profile.Count; i++)
{
try
{
dr = dt.NewRow();
dr["Id"] = jstring.profile[i].Id;
dr["FirstName"] = jstring.profile[i].FirstName;
dr["LastName"] = jstring.profile[i].LastName;
dt.Rows.Add(dr);
}
}
錯誤:
無法反序列化當前 JSON 數組,因為該類型需要 JSON object 才能正確反序列化。 要修復此錯誤,請將 JSON 更改為 JSON object 或將反序列化類型更改為數組或實現集合接口的類型,例如可以從 JSON 數組反序列化的 List。 還可以將 JsonArrayAttribute 添加到類型以強制它從 JSON 數組反序列化。
這個
[{
"Id": 1,
"FirstName": "Jason1",
"LastName": "Test1",
"Email": "123@automail.com",
"Eligible": true,
"InsertLogtime": "2022-02-21T00:51:59.917",
"Comment": null
},
{
"Id": 2,
"FirstName": "Jason2",
"LastName": "Test2",
"Email": "234@automail.com",
"Eligible": true,
"InsertLogtime": "2022-02-21T00:51:59.917",
"Comment": null
}
]
是一個數組([......])。 因此,正如錯誤所說,您必須反序列化為一個數組
像這樣
JsonConvert.DeserializeObject<Profile[]>(profile);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.