[英]JSON C# deserialization
我在從 JSON 字符串反序列化數據時遇到問題:
[{
"Example A": [{
"Parameter1": "Example A",
"Parameter2": "aaa",
"Parameter3": "2022-06-30 21:15:00.0000000",
"Value": 11.11
}
],
"Example B": [{
"Parameter1": "Example B",
"Parameter2": "ccc",
"Parameter3": "2022-06-30 21:15:00.0000000",
"Value": 33.33
}
],
"Example C": [
{
"Parameter1": "Example C",
"Parameter2": "eee",
"TimestampUTC": "2022-06-30 21:15:00.0000000",
"Value": null
},
{
"Parameter1": "Example C",
"Parameter2": "fff",
"Parameter3": "2022-06-30 21:15:00.0000000",
"Value": 44.44
}
]
}]
我嘗試過的是:
public class ExampleA
{
public string Parameter1 { get; set; }
public string Parameter2 { get; set; }
public string Parameter3 { get; set; }
public double Value { get; set; }
}
public class ExampleB
{
public string Parameter1 { get; set; }
public string Parameter2 { get; set; }
public string Parameter3 { get; set; }
public double Value { get; set; }
}
public class ExampleC
{
public string Parameter1 { get; set; }
public string Parameter2 { get; set; }
public string Parameter3 { get; set; }
public double Value { get; set; }
}
public class Examples
{
[JsonProperty("Example A")]
public List<ExampleA> ExampleA { get; set; }
[JsonProperty("Example B")]
public List<ExampleB> ExampleB { get; set; }
[JsonProperty("Example C")]
public List<ExampleC> ExampleC { get; set; }
}
但是當我嘗試用這個測試它時:
Examples someVar = JsonConvert.DeserializeObject<Examples>(JsonString);
Console.WriteLine(SomeVar.ExampleA.Count);
我收到此錯誤:
未處理的異常。 Newtonsoft.Json.JsonSerializationException:無法將當前 JSON 數組(例如 [1,2,3])反序列化為類型“MyProject.Examples”,因為該類型需要 JSON 對象(例如 {"name":"value"})來反序列化正確。
要修復此錯誤,請將 JSON 更改為 JSON 對象(例如 {"name":"value"})或將反序列化類型更改為數組或實現集合接口的類型(例如 ICollection、IList),例如 List
<T>
可以從 JSON 數組反序列化。 JsonArrayAttribute 也可以添加到類型中以強制它從 JSON 數組反序列化。
顯然我很難理解反序列化是如何工作的——我想要做的是這樣的:
foreach item in Example
// do something
foreach thing in item
// do something more
我意識到在這種情況下我很難掌握 JSON 格式。
我正在使用.NET Core。
你的 json 中有一個數組試試這個
List<Examples> someVar = JsonConvert.DeserializeObject<List<Examples>>(JsonString);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.