這個問題在這里已經有了答案: 使用動態鍵反序列化 JSON (4 個回答) 14 小時前關閉。
我有一個如下所示的 JSON 物件:
{
"preface": {
"title": "Preface",
"content": [
],
"navigation": [
{
"text": "Table of Contents",
"section": "table-of-contents"
}
]
},
"table-of-contents": {
"title": "The Adventures of Sherlock Holmes",
"content": [
],
"navigation": [
{
"text": "A Scandal in Bohemia",
"section": "a-scandal-in-bohemia"
},
{
"text": "The Red-Headed League",
"section": "the-red-headed-league"
},
{
"text": "Return to Preface",
"section": "preface"
}
]
},
"a-scandal-in-bohemia": {
"title": "A Scandal in Bohemia",
"content": [
"Chapter I",
"Chapter II",
"Chapter III"
],
"navigation": [
{
"text": "Chapter I",
"section": "bohemia-chapter-1"
},
{
"text": "Chapter II",
"section": "bohemia-chapter-2"
},
{
"text": "Chapter III",
"section": "bohemia-chapter-3"
},
{
"text": "Return to Table of Contents",
"section": "table-of-contents"
}
]
},
"bohemia-chapter-1": {
"title": "Chapter I",
"content": [
"To Sherlock Holmes she is always the woman. I have seldom heard him mention her under any other name. In his eyes she eclipses and predominates the whole of her sex. It was not that he felt any emotion akin to love for Irene Adler. All emotions, and that one particularly, were abhorrent to his cold, precise but admirably balanced mind. He was, I take it, the most perfect reasoning and observing machine that the world has seen, but as a lover he would have placed himself in a false position. He never spoke of the softer passions, save with a gibe and a sneer. They were admirable things for the observer--excellent for drawing the veil from men's motives and actions. But for the trained reasoner to admit such intrusions into his own delicate and finely adjusted temperament was to introduce a distracting factor which might throw a doubt upon all his mental results. Grit in a sensitive instrument, or a crack in one of his own high-power lenses, would not be more disturbing than a strong emotion in a nature such as his. And yet there was but one woman to him, and that woman was the late Irene Adler, of dubious and questionable memory.",
"..."
],
"navigation": [
{
"text": "Chapter II",
"section": "bohemia-chapter-2"
}
]
},
...
}
如您所見,它不是物件陣列,每個檔案都有唯一的名稱但結構相同。我想知道如何將其反序列化為 C# 物件串列。這是我到目前為止所擁有的。我的模型:
public class Document
{
public Dictionary<string, Section> Section { get; set; }
public override string ToString() => JsonSerializer.Serialize<Document>(this);
}
public class Section
{
public string Title { get; set; }
public List<string> Content { get; set; }
[JsonPropertyName("navigation")]
public List<Navigation> Navigations { get; set; }
public override string ToString() => JsonSerializer.Serialize<Section>(this);
}
以上是我如何序列化json文本檔案。我想將其反序列化為要在 Razor 視圖上顯示的物件串列。這是我的服務方法:
public IEnumerable<Document> GetDocuments()
{
using (var jsonFileReader = File.OpenText(JsonFileName))
{
return JsonSerializer.Deserialize<List<Document>>(jsonFileReader.ReadToEnd(),
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
}
我的 Index.html 代碼后面:
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public JsonFileService DocumentService;
public IEnumerable<Document> Documents { get; private set; }
public IndexModel(ILogger<IndexModel> logger, JsonFileService documentService)
{
_logger = logger;
DocumentService = documentService;
}
public void OnGet()
{
Documents = DocumentService.GetDocuments();
}
}
最后在我的 Razor 視圖中,我只有這個foreach回圈:
foreach (var document in Model.Documents)
{
<h3>@document.Section.Title</h3>
}
當我運行程式時,我收到以下錯誤和堆疊跟蹤:
JsonException: The JSON value could not be converted to System.Collections.Generic.List`1[WebApp.Models.Document]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
System.Text.Json.Serialization.JsonCollectionConverter<TCollection, TElement>.OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, out TCollection value)
System.Text.Json.Serialization.JsonConverter<T>.TryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, out T value)
System.Text.Json.Serialization.JsonConverter<T>.ReadCore(ref Utf8JsonReader reader, JsonSerializerOptions options, ref ReadStack state)
System.Text.Json.JsonSerializer.ReadFromSpan<TValue>(ReadOnlySpan<byte> utf8Json, JsonTypeInfo jsonTypeInfo, Nullable<int> actualByteCount)
System.Text.Json.JsonSerializer.ReadFromSpan<TValue>(ReadOnlySpan<char> json, JsonTypeInfo jsonTypeInfo)
System.Text.Json.JsonSerializer.Deserialize<TValue>(string json, JsonSerializerOptions options)
WebApp.Services.JsonFileService.GetDocuments() in JsonFileService.cs
return JsonSerializer.Deserialize<List<Document>>(jsonFileReader.ReadToEnd(),
WebApp.Pages.IndexModel.OnGet() in Index.cshtml.cs
Documents = DocumentService.GetDocuments();
我覺得我在這里錯過了一個非常簡單的步驟。似乎因為 JSON 物件不是物件陣列,反序列化器無法將其轉換為 IEnumerable。有人可以指導我如何將此 JSON 轉換為 C# 物件串列嗎?
uj5u.com熱心網友回復:
你的 JSON 是你定義的值的形狀 Section
public Dictionary<string, Section> Section { get; set; }
即,它是一個Dictionary<string,Section>. 您不能將其反序列化為其中的一個List。您必須將其反序列化為該型別
public Dictionary<string,Section> GetDocuments()
{
using (var jsonFileReader = File.OpenText(JsonFileName))
{
return JsonSerializer.Deserialize<Dictionary<string,Section>>(jsonFileReader.ReadToEnd(),
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
}
實體:https : //dotnetfiddle.net/iUGsR7
uj5u.com熱心網友回復:
似乎因為 JSON 物件不是物件陣列,反序列化器無法將其轉換為 IEnumerable
是的,它不是一個物件陣列,它是一個包含其他物件的物件,我相信使用默認的序列化器/反序列化器將無法解決這個 JSON。
除非您最終使用動態物件(可以是 JObject)然后將其轉換為另一個結構,否則唯一的方法是為此特定情況撰寫自定義序列化程式并構建此 JSON 的變通方法。
你可以試試這個:
var obj = JsonConvert.DeserializeObject<JObject>(json);
var childrenObjects = obj.Children();
這將為您提供此 JSON 上的四個元素的串列,然后您可以將其轉換為適當的物件并使用它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376085.html
下一篇:無法從api回應決議json
