简体   繁体   中英

Can't parse JSON in C#?

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. 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 ?

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

You can deserialize in JArray

JArray array = JsonConvert.DeserializeObject<JArray>(json);
foreach (var item in array)
{
    Console.WriteLine(item["fuzzy"]); // Prints 12345
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM