我正在尝试使用StreamReader
:
using (var jsonReader = new StreamReader(pathToMyJsonFile))
{
string json = jsonReader.ReadToEnd();
dynamic array = JsonConvert.DeserializeObject(json);
foreach (var item in array)
{
Console.WriteLine(item.fuzzy);
}
}
我的json:
[
{
"fuzzy": "12345",
"name": "{jon-errand}",
"email": "person@gmail.com",
"lights": "red",
"friends": "Elizabeth",
"traits": {
"Hair": "brown",
"Eyes": "yellow"
}
}
]
我得到例外:Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject.
我试着看看这里张贴的SO答案,但我确信我的json是一个真正的数组。如果不改变上面的json,我怎么能以一种有用的方式读取这个json文件,这样我就可以取出特定的字段?比如把email
字段写成person@gmail.com
?
var obj = JsonConvert.DeserializeObject<List<Item>>(File.ReadAllText(pathToMyJsonFile));
和你的类
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; }
}
编辑
dynamic array = JsonConvert.DeserializeObject(File.ReadAllText(pathToMyJsonFile));
foreach (var item in array)
{
Console.WriteLine(item.name + " " + item.traits.Hair);
}
可以在JArray中反序列化
JArray array = JsonConvert.DeserializeObject<JArray>(json);
foreach (var item in array)
{
Console.WriteLine(item["fuzzy"]); // Prints 12345
}