5

我需要你的帮助。我是 C# 新手,所以我将不胜感激!所以我做了一个程序来解析一个 json 文件并将其放入一个对象中。我的程序如下所示:

var path = (@"C:\sim\input7.json");
using (StreamReader reader = File.OpenText(path))
{
   JObject SimData = JObject.Parse(reader.ReadLine());
   Console.WriteLine("Object ID: " + SimData["_id"]);
   Console.WriteLine("ID: " + SimData["id"]);
   Console.WriteLine("Day: " + SimData["day"]);
   Console.WriteLine("Value: " + SimData["value"]);

首先,我在我的 json 文件中只使用了一行,它工作正常。现在我有多行,例如:

{ "_id" : "_id1" , "id" : "100", "day" : "5", "value" : "90.38", "time" : "000000" }
{ "_id" : "_id2", "id" : 100, "day" : 5, "value" : 89.79000000000001, "time" : "000100" }

我的问题是,例如,如果我想要Console.WriteLine();每个值该怎么办!

我尝试了几件事,但无法解决这个问题。我有相同的输入文件。我现在试过了:

using (StreamReader reader = new StreamReader(path))
                 {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                     {
                        list.Add(line);
                        JObject SD = JObject.Parse(line);
                        Console.WriteLine(SD["day"]);
                     }
              }

只想为每一行写出“价值”!

4

2 回答 2

0

你可能想要一个合适的 json 文件,它会更容易阅读(也更干净):

{ "_id" : "_id1" , "id" : "100", "day" : "5", "value" : "90.38", "time" : "000000" }
{ "_id" : "_id2", "id" : 100, "day" : 5, "value" : 89.79000000000001, "time" : "000100" }

这不是 json

[{ "_id" : "_id1" , "id" : "100", "day" : "5", "value" : "90.38", "time" : "000000" },
{ "_id" : "_id2", "id" : 100, "day" : 5, "value" : 89.79000000000001, "time" : "000100" }]

这是一个 json 数组。

如果您可以拥有此 json 文件,那么您可以使用Json.Net为您正在解析的对象创建一个类将其作为列表轻松读取:

public class IdObject
{
    public string _id { get; set; }
    public int id { get; set; }
    public int day { get; set; }
    public int value { get; set; }
    public int time { get; set; }
}

然后 :

List<IdObject> list = JsonConvert.DeserializeObject<List<IdObject>>(jsonString);
Console.WriteLine(list[0]._id);

结果:_id1

于 2014-05-30T09:12:40.650 回答
0

分别解析每个 JSON 文件:

foreach(DirectoryInfo directoryInfo in new DirectoryInfo(@"C:\sim\").getDirectories());
{
   using (StreamReader reader = File.OpenText(directoryInfo.FullName))
{
   JObject SimData = JObject.Parse(reader.ReadLine());
   Console.WriteLine("Object ID: " + SimData["_id"]);
   Console.WriteLine("ID: " + SimData["id"]);
   Console.WriteLine("Day: " + SimData["day"]);
   Console.WriteLine("Value: " + SimData["value"]);
}
}
于 2012-10-18T14:09:29.377 回答