我在 C# 中使用 System.Text.Json 從 json 讀取到 IEnumerable 時遇到問題...
那是錯誤:
System.Text.Json.JsonException: The JSON value could not be converted to System.Collections.Generic.Dictionary`2[System.String,System.String[]]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
以下幾行包含我的代碼:
private static Dictionary<string, string[]>? GetStaticMedicalAdvisors()
{
// TODO - read from json
// TODO - convert to contact
// TODO - add contacts to list
// TODO - DO NOT USE NEWTONSOFT.JSON (use System.Text.Json)
// TODO - return list
var json = System.IO.File.ReadAllText("MedicalAdvisors.json");
var dict = JsonSerializer.Deserialize<Dictionary<string, String[]>>(json);
return dict;
}
這是我的MedicalAdvisors.json:
[
{
"name": "Franz Immer",
"endpoint": "000",
"country": "CH"
},
{
"name": "Nathalie Krügel",
"endpoint": "000",
"country": "CH"
}
]
uj5u.com熱心網友回復:
您的 json 將反序列化為:
var result = JsonSerializer.Deserialize<Dictionary<string,string>[]>(json);
但是,創建一個匹配結構的型別不是更有用嗎?
public class UserInfo
{
public string name { get; set; }
public string endpoint { get; set; }
public string country { get; set; }
}
var result = JsonSerializer.Deserialize<UserInfo[]>(json);
uj5u.com熱心網友回復:
需要根據Model結構反序列化json資料。NewtonSoft 有一個反序列化的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366625.html
上一篇:捕獲Json未知欄位的例外
