简体   繁体   中英

To parse JSON data from text file using c# winforms

I have numbers of text files containing Json data, i want to parse all required data from all those files. I am creating C# windows app to do this task. please help me for same, thanx a lot in advance

Here is my text file data sample:

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 
        }

First you need to extract the JSON from your file; to do this you could do something like this:

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;
}

Then once you have your json data, use a parser like the one by NewtonSoft to parse the json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM