我怎么能得到json字符串中的名称和值

时间:2016-01-28 11:41:28

标签: c# json

我怎样才能获得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
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

这应该可以使用JavaScriptSerializer Class 但是,反序列化器可能无法对字符串进行反序列化。在这种情况下,您可以将字符串初步转换为反序列化器“可理解”的形式。

另一种可能的方法是使用Regex 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);
        }