Json和解析C#

时间:2012-10-18 13:58:26

标签: json.net

我需要你的帮助。我是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"]);
                     }
              }

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

2 个答案:

答案 0 :(得分: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"]);
}
}

答案 1 :(得分: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