我試圖在我的 ASP.NET Core 應用程式中使用 Newtonsoft 將 JSON 檔案決議為物件,但我不斷收到此錯誤:
Newtonsoft.Json.JsonReaderException:'決議值時遇到意外字符:{。路徑'palette.swatch',第 7 行,位置 15。
我試過使用StreamReader班級和現在的MemoryStream班級。我已經確認在線驗證了 JSON 并檢查了它也是 UTF-8。兩種方式我都會收到相同的錯誤。我還手動檢查了 JSON,但看不到任何使其不可讀的內容。
這是引發例外的方法:
public async Task<int> PostDefinition(IFormFile file)
{
MemoryStream ms = new MemoryStream();
file.CopyTo(ms);
byte[] bytes = ms.ToArray();
string s = Encoding.UTF8.GetString(bytes);
Definition definition = Newtonsoft.Json.JsonConvert.DeserializeObject<Definition>(s);
Definition x = ObjectMapper.Map<Definition>(Definition);
return await _definitions.InsertAndGetIdAsync(x);
}
這是引發錯誤的 JSON 片段:
{
"name": "Definition",
"id": 2,
"palette": {
"name": "Test Palette",
"default": false,
"swatch": {
"colors": {
"Color 1": "transparent",
"Color 2": "transparent",
"Color 3": "transparent",
"Color 4": "transparent",
"Color 5": "transparent",
"Color 6": "transparent",
"Color 7": "transparent",
"Color 8": "transparent"
}
}
}
}
什么可能導致例外,我可以嘗試解決什么?我已經嘗試過搜索,但我嘗試的任何方法似乎都不起作用。
uj5u.com熱心網友回復:
這對我有用
Definition definition = Newtonsoft.Json.JsonConvert.DeserializeObject<Definition>(s);
班級
public partial class Definition
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("palette")]
public Palette Palette { get; set; }
}
public partial class Palette
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("default")]
public bool Default { get; set; }
[JsonProperty("swatch")]
public Swatch Swatch { get; set; }
}
public partial class Swatch
{
[JsonProperty("colors")]
public Dictionary<string,string> Colors { get; set; }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425431.html
標籤:asp.net-mvc asp.net 核心 json.net 流式阅读器 记忆流
下一篇:如何在頁面之間創建鏈接?
