Badre Arras
Badre Arras

Reputation: 63

Loop through each item in .json file

I have .Json file and I want to loop through each item in it and assign for each variable the appropriate value, I get exception saying :

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.

Am I missing something?

Here is what I have done so far:

    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;
        }
    }

Here is the Spec class:

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

and finally my JSON file:

{

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

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

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

Upvotes: 1

Views: 1699

Answers (2)

Joe Doe
Joe Doe

Reputation: 11

I had the same problem. But instead of using that TestClass from @T McKeown I would suggest another solution.

var _spec = JsonConvert.DeserializeObject<Dictionary<string, Spec>>(json);

With an foreach loop or other loop you can now use the dictionary which contains all your values

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

Upvotes: 1

T McKeown
T McKeown

Reputation: 12857

Your JSON is not a list, it's an object with properties of objects. For example, this type looks more like your JSON:

public class TestClass{

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

  ...
}

This would be how you'd deserialize this:

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

Upvotes: 3

Related Questions