【发布时间】:2022-01-03 18:18:55
【问题描述】:
使用 System.Text.Json 在 C# 中从 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"
}
]
【问题讨论】:
-
查看一小部分 MedicalAdvisors.json 样本可能会有所帮助。
-
这就是字典的 json 表示形式
的样子。您文件中的数据是否遵循此模式? {"key1":["a","b","c"],"key2":["d","e","f"],"key3":["g","h","i"]} -
@benjamin 我编辑了问题。
-
@Crowcoder 是的,看看我的 json 文件,我刚才将它添加到我的问题中。
-
不,看起来不一样。你有一个项目数组,而不是字典。
标签: c# json type-conversion system.text.json