1

I am trying to read a local .json file using StreamReader:

My code:

using (var jsonReader = new StreamReader(pathToMyJsonFile)) 
{
     string json = jsonReader.ReadToEnd();
     dynamic array = JsonConvert.DeserializeObject(json);
     foreach (var item in array)
     {
         Console.WriteLine(item.fuzzy);
     }

}

My json:

[
    {
        "fuzzy": "12345",
        "name": "{jon-errand}",
        "email": "person@gmail.com",
        "lights": "red",
        "friends": "Elizabeth",
        "traits": {
            "Hair": "brown",
            "Eyes": "yellow"
        }
    }
]

I get the exception: Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. I have tried looking at the SO answer posted here but I am sure my json is a real array. Without changing the above json, how can I read this json file in a useful way so I can pull out specific fields? Such as getting the email field as person@gmail.com?

Community
  • 1
  • 1
user3772119
  • 484
  • 3
  • 7
  • 16

2 Answers2

5
var obj  = JsonConvert.DeserializeObject<List<Item>>(File.ReadAllText(pathToMyJsonFile));

And your classes

public class Traits
{
    public string Hair { get; set; }
    public string Eyes { get; set; }
}

public class Item
{
    public string fuzzy { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public string lights { get; set; }
    public string friends { get; set; }
    public Traits traits { get; set; }
}

EDIT

dynamic array = JsonConvert.DeserializeObject(File.ReadAllText(pathToMyJsonFile));

foreach (var item in array)
{
    Console.WriteLine(item.name + " " + item.traits.Hair);
}
EZI
  • 15,209
  • 2
  • 27
  • 33
  • 1
    Json.Net should handle dynamic's fine. http://stackoverflow.com/questions/4535840/deserialize-json-object-into-dynamic-object-using-json-net – Liam Jul 08 '14 at 15:30
  • Is there any way to do this without making additional classes? – user3772119 Jul 08 '14 at 15:31
  • @Liam Of course, But getting help from compiler can be better in most cases. – EZI Jul 08 '14 at 15:35
  • How does your edit differ from the code in the question? – svick Jul 08 '14 at 15:36
  • what's the difference between your answer and the OPs? They seem practically identical? – Liam Jul 08 '14 at 15:36
  • 1
    Thanks for the help! You may want to clarify in your answer that the code above and below the `EDIT` are mutually exclusive and work independent of each other. – user3772119 Jul 08 '14 at 15:55
-1

You can deserialize in JArray

JArray array = JsonConvert.DeserializeObject<JArray>(json);
foreach (var item in array)
{
    Console.WriteLine(item["fuzzy"]); // Prints 12345
}
Alexandre Pepin
  • 1,816
  • 3
  • 20
  • 36