Skip to main content
 首页 » 编程设计

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

2024年02月06日12dflying

我有 .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));