在C#中迭代和解析JSON字符串时,是否有办法知道最后一个令牌?

时间:2019-02-01 10:41:59

标签: c# json

我正在解析字符串上的一些JSON数据,以将其传递给具有自定义格式的文件。 但是我需要知道哪个是文件的最后一个标记,以便我使用“}”而不是“}”(即逗号不具有正确的语法)关闭标签。

我尝试使用Last属性获取最后一个令牌,但是它不起作用。

这是我用来解析数据并写入文件的功能(它还会将所需的数据打印到终端,但不会以JSON数据打印,这就是我首先解析它的原因):

private static void ParseData()
        {
            JObject jsonData;

            try
            {
                using (StreamWriter file = new StreamWriter(Globals.dataFile))
                {
                    file.WriteLine("{");

                    jsonData = JObject.Parse(Globals.json);
                    Console.WriteLine("*********************************************");
                    foreach (JToken tokens in jsonData["indicator"]["values"])
                    {
                        Console.WriteLine("Fecha y hora: " + tokens["datetime"] + " Valor: " + tokens["value"] + Environment.NewLine + "*********************************************");
                        file.Write(Environment.NewLine + "\t{" + Environment.NewLine + "\t\t\"datetime\": " + tokens["datetime"] + ",");
                        file.WriteLine("\t\t\"value\": " + tokens["value"]);
                        if (tokens != tokens.Last)
                        {
                            file.WriteLine("\t},");
                            Console.WriteLine("\t},");
                        }
                        else
                        {
                            Console.WriteLine("\t}");
                        }
                    }

                    file.WriteLine("}");
                }
            }
            catch (Exception ex)
            {
                PrintExceptionMessage(ex);
            }
        }

这是我正在格式化的JSON文件的格式:

{
    "indicator": {
        "name": "Precio medio horario final contratación libre suma de componentes",
        "short_name": "Precio medio horario final c.libre suma",
        "id": 10214,
        "composited": true,
        "step_type": "linear",
        "disaggregated": false,
        "magnitud": [{
                "name": "Precio",
                "id": 23
            }
        ],
        "tiempo": [{
                "name": "Hora",
                "id": 4
            }
        ],
        "geos": [{
                "geo_id": 8741,
                "geo_name": "Península"
            }
        ],
        "values_updated_at": "2019-01-31T08:05:32.000+01:00",
        "values": [{
                "value": 49.38,
                "datetime": "2019-01-31T01:00:00.000+01:00",
                "datetime_utc": "2019-01-31T00:00:00Z",
                "tz_time": "2019-01-31T00:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 47.46,
                "datetime": "2019-01-31T02:00:00.000+01:00",
                "datetime_utc": "2019-01-31T01:00:00Z",
                "tz_time": "2019-01-31T01:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 46.82,
                "datetime": "2019-01-31T03:00:00.000+01:00",
                "datetime_utc": "2019-01-31T02:00:00Z",
                "tz_time": "2019-01-31T02:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 46.5,
                "datetime": "2019-01-31T04:00:00.000+01:00",
                "datetime_utc": "2019-01-31T03:00:00Z",
                "tz_time": "2019-01-31T03:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 47.36,
                "datetime": "2019-01-31T05:00:00.000+01:00",
                "datetime_utc": "2019-01-31T04:00:00Z",
                "tz_time": "2019-01-31T04:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 50.05,
                "datetime": "2019-01-31T06:00:00.000+01:00",
                "datetime_utc": "2019-01-31T05:00:00Z",
                "tz_time": "2019-01-31T05:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 56.61,
                "datetime": "2019-01-31T07:00:00.000+01:00",
                "datetime_utc": "2019-01-31T06:00:00Z",
                "tz_time": "2019-01-31T06:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 65.58,
                "datetime": "2019-01-31T08:00:00.000+01:00",
                "datetime_utc": "2019-01-31T07:00:00Z",
                "tz_time": "2019-01-31T07:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 66.59,
                "datetime": "2019-01-31T09:00:00.000+01:00",
                "datetime_utc": "2019-01-31T08:00:00Z",
                "tz_time": "2019-01-31T08:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 66.49,
                "datetime": "2019-01-31T10:00:00.000+01:00",
                "datetime_utc": "2019-01-31T09:00:00Z",
                "tz_time": "2019-01-31T09:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 65.54,
                "datetime": "2019-01-31T11:00:00.000+01:00",
                "datetime_utc": "2019-01-31T10:00:00Z",
                "tz_time": "2019-01-31T10:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 63.71,
                "datetime": "2019-01-31T12:00:00.000+01:00",
                "datetime_utc": "2019-01-31T11:00:00Z",
                "tz_time": "2019-01-31T11:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 61.94,
                "datetime": "2019-01-31T13:00:00.000+01:00",
                "datetime_utc": "2019-01-31T12:00:00Z",
                "tz_time": "2019-01-31T12:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 56.58,
                "datetime": "2019-01-31T14:00:00.000+01:00",
                "datetime_utc": "2019-01-31T13:00:00Z",
                "tz_time": "2019-01-31T13:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }, {
                "value": 56.08,
                "datetime": "2019-01-31T15:00:00.000+01:00",
                "datetime_utc": "2019-01-31T14:00:00Z",
                "tz_time": "2019-01-31T14:00:00.000Z",
                "geo_id": 8741,
                "geo_name": "Península"
            }
        ]
    }
}

我仅从此处获取“值”和“日期时间”数据。

我现在获取的文件具有这种格式(真的很不好,很抱歉):

{

    {
        "datetime": 01/02/2019 01:00:00,        "value": 48,68
    },

    {
        "datetime": 01/02/2019 02:00:00,        "value": 45,7
    },

    {
        "datetime": 01/02/2019 03:00:00,        "value": 44,1
    },

    {
        "datetime": 01/02/2019 04:00:00,        "value": 44,53
    },

    {
        "datetime": 01/02/2019 05:00:00,        "value": 46,87
    },

    {
        "datetime": 01/02/2019 06:00:00,        "value": 49,84
    },

    {
        "datetime": 01/02/2019 07:00:00,        "value": 56,69
    },

    {
        "datetime": 01/02/2019 08:00:00,        "value": 62,5
    },
}

我想得到的是:

{
    {
        "datetime": 01/02/2019 01:00:00,
        "value": 48,68
    },{
        "datetime": 01/02/2019 02:00:00,
        "value": 45,7
    },{
        "datetime": 01/02/2019 03:00:00,
        "value": 44,1
    },{
        "datetime": 01/02/2019 04:00:00,
        "value": 44,53
    },{
        "datetime": 01/02/2019 05:00:00,
        "value": 46,87
    },{
        "datetime": 01/02/2019 06:00:00,
        "value": 49,84
    },{
        "datetime": 01/02/2019 07:00:00,
        "value": 56,69
    },{
        "datetime": 01/02/2019 08:00:00,
        "value": 62,5
    }
}

非常感谢您,对不起。我真的是JSON的新手,并在C#上对其进行格式化。

1 个答案:

答案 0 :(得分:0)

您需要将json中选择的键/值对解析为类对象列表,然后将其再次保存到新文件中,例如

private static void ParseData()
{
    string json = File.ReadAllText(@"Path to your input json file");

    JObject jsonData = JObject.Parse(json);

    List<MyCustomClass> output = new List<MyCustomClass>();

    foreach (JToken tokens in jsonData["indicator"]["values"])
    {
        output.Add(new MyCustomClass { datetime = tokens["datetime"].ToString(), value = tokens["value"].ToString() });
    }

    File.WriteAllText(@"Path to your output json file", JToken.FromObject(output).ToString());
}

并且您需要一个类对象来解析键/值对,

class MyCustomClass
{
    public string datetime { get; set; }
    public string value { get; set; }
}

输出:

[
  {
    "datetime": "31-01-2019 05:30:00 AM",
    "value": "49.38"
  },
  {
    "datetime": "31-01-2019 06:30:00 AM",
    "value": "47.46"
  },
  {
    "datetime": "31-01-2019 07:30:00 AM",
    "value": "46.82"
  },
  {
    "datetime": "31-01-2019 08:30:00 AM",
    "value": "46.5"
  },
  {
    "datetime": "31-01-2019 09:30:00 AM",
    "value": "47.36"
  },
  {
    "datetime": "31-01-2019 10:30:00 AM",
    "value": "50.05"
  },
  {
    "datetime": "31-01-2019 11:30:00 AM",
    "value": "56.61"
  },
  {
    "datetime": "31-01-2019 12:30:00 PM",
    "value": "65.58"
  },
  {
    "datetime": "31-01-2019 01:30:00 PM",
    "value": "66.59"
  },
  {
    "datetime": "31-01-2019 02:30:00 PM",
    "value": "66.49"
  },
  {
    "datetime": "31-01-2019 03:30:00 PM",
    "value": "65.54"
  },
  {
    "datetime": "31-01-2019 04:30:00 PM",
    "value": "63.71"
  },
  {
    "datetime": "31-01-2019 05:30:00 PM",
    "value": "61.94"
  },
  {
    "datetime": "31-01-2019 06:30:00 PM",
    "value": "56.58"
  },
  {
    "datetime": "31-01-2019 07:30:00 PM",
    "value": "56.08"
  }
]