[英]I am trying to deserialize a JSON into a list of objects using .NET 3.1
我有以下 Json:
{
"Id":"2727",
"Region":"US",
"Data":[
{
"Title":"Director",
"JobDescription":"Coordinates the department activity",
"Department":"HR"
},
{
"Title":"Programmer",
"JobDescription":"Enterprise software developer",
"Department":"FR"
}
]
}
我的格式如下所示:
public class Data
{
public string Title { get; set; }
public string JobDescription { get; set; }
public string Department { get; set; }
}
public class Format
{
public string Id { get; set; }
public string Region { get; set; }
public List<Data> Data {get; set;}
}
我試圖像這樣反序列化它:
var objects = JsonConvert.DeserializeObject<IEnumerable<Format>>(File.ReadAllText("mockJson.json")).ToList();
我收到此異常:
Newtonsoft.Json.dll 中發生類型為“Newtonsoft.Json.JsonSerializationException”的未處理異常無法將當前 JSON 對象(例如 {"name":"value"})反序列化為類型 'System.Collections.Generic.IEnumerable`1[ JSONParsingExample.Format]' 因為該類型需要一個 JSON 數組(例如 [1,2,3])才能正確反序列化。 要修復此錯誤,請將 JSON 更改為 JSON 數組(例如 [1,2,3])或更改反序列化類型,使其成為普通的 .NET 類型(例如,不是像整數這樣的原始類型,而不是像這樣的集合類型)可以從 JSON 對象反序列化的數組或列表)。 JsonObjectAttribute 也可以添加到類型中以強制它從 JSON 對象反序列化。 路徑“GlobalOrgId”,第 2 行,位置 15。
只是將其發布為答案,因為我認為值得讓它更加明顯。 我認為方法調用在 json 中的嵌套列表會出現一些問題,但我很高興看到它有效。
Format format = JsonConvert.DeserializeObject<Format>(File.ReadAllText("mockJson.json"));
我檢查了元素,它們似乎都在它們應該在的地方。
請小心,因為JsonConvert.DeserializeObject<T>
返回類型為T
的對象,而不是IEnumerable<T>
。
在 .NET 中使用 JSON 時,我建議轉向新的內置內容。
https://devblogs.microsoft.com/dotnet/net-core-image-processing/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.