我如何在我拥有的 json 字符串中获取名称和值

本文关键字:获取 json 拥有 字符串 | 更新日期: 2023-09-27 18:32:13

如何在我拥有json字符串中获取名称和值:

{
  "AccYearsList": [
    {
      "start_date": 1453766400
    },
    {
      "end_date": 1485302400
    },
    {
      "start_date": 1454198400
    },
    {
      "end_date": 1485734400
    },
    {
      "start_date": 1382400
    },
    {
      "end_date": 32918400
    },
    {
      "start_date": 1382400
    },
    {
      "end_date": 32918400
    },
    {
      "start_date": 1382400
    },
    {
      "end_date": 32918400
    },
    {
      "start_date": 1382400
    },
    {
      "end_date": 32918400
    },
    {
      "start_date": 1382400
    },
    {
      "end_date": 32918400
    },
    {
      "start_date": 1382400
    },
    {
      "end_date": 32918400
    },
    {
      "start_date": 1382400
    },
    {
      "end_date": 32918400
    },
    {
      "start_date": 1382400
    },
    {
      "end_date": 32918400
    },
    {
      "start_date": 1382400
    },
    {
      "end_date": 32918400
    },
    {
      "start_date": 1382400
    },
    {
      "end_date": 32918400
    },
    {
      "start_date": 1453852800
    },
    {
      "end_date": 1485388800
    },
    {
      "start_date": 1453852800
    },
    {
      "end_date": 1485388800
    }
  ]
}

我如何在我拥有的 json 字符串中获取名称和值

应该是可以使用JavaScriptSerializer Class来实现的但是,反序列化程序可能无法按原样反序列化字符串。在这种情况下,您可以将字符串初步转换为反序列化程序"可理解"的形式。

另一种可能的方法是使用正则表达式类。 如下所示:

            const string inputStr = "{" +
                                "'"AccYearsList'": [" +
                                "{'"start_date'": 1453766400}," +
                                "{'"end_date'": 1485302400}," +
                                "{'"start_date'": 1454198400}," +
                                "{'"end_date'": 1485734400}," +
                                "{'"start_date'": 1382400}," +
                                "{'"end_date'": 32918400}," +
                                "{'"start_date'": 1382400}," +
                                "{'"end_date'": 32918400}]}";
        const string pattern = @"start_date.:'s*('d+)}.+?end_date.:'s*('d+)}";
        var re = new Regex(pattern);
        var matches = re.Matches(inputStr);
        foreach (Match match in matches)
        {
            var startDate = match.Groups[1];
            var endDate = match.Groups[2];
            Console.WriteLine("start_date: '{0}'", startDate);
            Console.WriteLine("end_date: '{0}'", endDate);
        }