c# - 遍历 .json 文件中的每个项目

标签 c# wpf

我有 .Json 文件,我想遍历其中的每个项目并为每个变量分配适当的值,我得到异常提示:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WpfApplication1.MainWindow+MyItem]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

我错过了什么吗?

这是我到目前为止所做的:

    private void ReadFromJson()
    {
        string PinH, PinL;

        StreamReader r = new StreamReader(@"C:\Users\Badre\Desktop\Spec.json");
        string json = r.ReadToEnd();

        List<Spec> _spec = (List<Spec>)Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(List<Spec>));

        foreach (var item in _spec)
        {
            PinH = item.PinHigh;
            PinL = item.PinLow;
        }
    }

这是规范类:

public class Spec
    {
        public string PinHigh {get; set;}
        public string PinLow { get; set; }
    }

最后是我的 JSON 文件:

{

    "ResistanceR10":
        {
            "PinHigh": "XCI2_14",
            "PinLow": "XCBB1_2"
        },

    "ResistanceR22":
        {
            "PinHigh": "XCI47",
            "PinLow": "XCBB18"
        },

    "DiodeV18":
        {
            "PinHigh": "XCI47",
            "PinLow": "XCBB18"
        },
    "CapacitanceC1":
        {
            "PinHigh": "XCI47",
            "PinLow": "XCBB18"
        }
}

最佳答案

您的 JSON 不是列表,它是具有对象属性的对象。例如,这种类型看起来更像您的 JSON:

public class TestClass{

  public Spec ResistanceR10 { get; set; }
  public Spec ResistanceR22 { get; set; }

  ...
}

这就是你反序列化它的方式:

TestClass _spec = (TestClass)Newtonsoft.Json.JsonConvert.DeserializeObject(json,  typeof(TestClass));

关于c# - 遍历 .json 文件中的每个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27760025/

相关文章:

c# - 在多个线程中将 Stream 读取到 MemoryStream

c# - 使用 Newtonsoft 在 C# 中使用 JSON Schema 验证 JSON

c# - 在DataTrigger中未一致地调用Setter

c# - 使用 System.Windows.Media.Animation 移动按钮动画

c# - WPF 有条件地启用键绑定(bind)

C# 不以 4 个字符开头的字符串的正则表达式

c# - 通过 WCF 自托管 2000 多个 Web 服务

wpf - 如何在 WPF Datagrid 上启用滚动条?

c# - Datagrid-复选框选择和取消选择

WPF 拆分器可见性