使用c#winforms从文本文件解析JSON数据

时间:2014-06-21 16:15:40

标签: c# json winforms json.net

我有大量包含Json数据的文本文件,我想从所有这些文件中解析所有必需的数据。我正在创建C#windows app来完成这项任务。 请提前帮助我,而不是提前很多

这是我的文本文件数据样本:

Name: sample testname
Username: sampleXYZ
Time zone: SampleTimezone
Language: EN
Json: {
  "id": 600723423551234234234,
  "id_str": "600723423551234234234",
  "name": "sample testname",
  "screen_name": "sampleXYZ",
  "location": "sample Location",
  "description": "sampleDescritpin",
  "url": null,
  "entities": {       "description": {
  "urls": []
    }
  },
     //some unwanted data in between 
        }

1 个答案:

答案 0 :(得分:0)

首先,您需要从文件中提取JSON;要做到这一点你可以做这样的事情:

static string ExtractJSON(string path)
{
    var file = File.ReadAllText(path);
    var brackets = 0;
    var json = "";

    foreach (var c in file)
    {
        if (c == '{') // if { encountered, go in a level
            brackets++;
        else if (c == '}') // if } encountered go out a level
        {
            brackets--;
            if (brackets == 0) 
                json += c.ToString(); // get the last bracket
        }

        if (brackets > 0) // ignore everything that isn't within the brackets
            json += c.ToString();
    }
    return json;
}

然后,一旦你有了你的json数据,使用像NewtonSoft那样的解析器来解析json