-1

I'm trying to get covid-19 results (only information about Iran) from an Api and show it on a textbox.

and the full result (all countries) that i get from the Api is a json format.

so to get only Iran section i made a Function that loops through lines of the string one by one and check if in that line there is a "{" and if yes get index of that and continue checking if in another line there is a "}" and get index of that too then check if between these, there is "Iran" then add this text (from "{" to "}") in a string:

private string getBetween(string strSourceText, string strStartingPosition, string strEndingPosition)
{
    int Starting_CurlyBracket_Index = 0;
    int Ending_CurlyBracket_Index = 0;
    
    string FinalText = null;
    
    bool isTurnTo_firstIf = true;
    
    foreach (var line in strSourceText.Split('\r', '\n'))
    {
        if (isTurnTo_firstIf == true)
        {
            if (line.Contains(strStartingPosition))
            {
                Starting_CurlyBracket_Index = line.IndexOf(strStartingPosition); //i think problem is here
    
                isTurnTo_firstIf = false;
            }
        }
    
        else if (isTurnTo_firstIf == false)
        {
            if (line.Contains(strEndingPosition))
            {
                Ending_CurlyBracket_Index = line.IndexOf(strEndingPosition); //i think problem is here
    
                if (strSourceText.Substring(Starting_CurlyBracket_Index, Ending_CurlyBracket_Index - Starting_CurlyBracket_Index).Contains("Iran")) //error here
                {
                    FinalText = strSourceText.Substring(Starting_CurlyBracket_Index, Ending_CurlyBracket_Index - Starting_CurlyBracket_Index);
    
                    break;
                }
                else
                {
                    isTurnTo_firstIf = true;
                }
            }
        }
    }
    
   return FinalText;
}

and i call the function like this:

string OnlyIranSection = getBetween(Sorted_Covid19_Result, "{", "}"); //Sorted_Covid19_Result is the full result in json format that converted to string
textBox1.Text = OnlyIranSection;

but i get this Error:

enter image description here

and i know.. its because it gets indexes in the current line but what i need is getting that index in the strSourceText so i can show only this section of the whole result:

enter image description here

hamidrezas120
  • 35
  • 1
  • 8
  • 4
    You need to use some JSON library to retrieve data. Coding like this is pointless. – apocalypse Aug 10 '20 at 12:10
  • nice starting point for parsing JSON-data: https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c – Andreas Aug 10 '20 at 12:11
  • As colleague wrote above, you should use json to read data. – Silny ToJa Aug 10 '20 at 12:14
  • but think that i converted from json to regular text using json parsing, the problem is still i dont know how to get only the information of iran? still i need to use some foreach or something, right? – hamidrezas120 Aug 10 '20 at 12:17
  • nice suggestion but i posted this question for learning how to get index of the character in the multiline string while looping through lines and the problem is, this will get me the index of the character on the current line while what i want is get that index in the whole full multiline text – hamidrezas120 Aug 10 '20 at 12:29
  • @hamidrezas120 Use a JSON-parsing library with LINQ to make your life so much less painful. – Ian Kemp Aug 10 '20 at 12:31
  • @hamidrezas120 I updated my answer. I hope it can help you. Happy coding. – tontonsevilla Aug 10 '20 at 13:48

1 Answers1

2

USING JSON
As per the comments I read it was really needed to use JSON utility to achieve your needs easier.

You can start with this basic example:

static void Main(string[] args)
    {
        string jsonString = @"{
                                ""results"": [
                                                {""continent"":""Asia"",""country"":""Indonesia""},
                                                {""continent"":""Asia"",""country"":""Iran""},
                                                {""continent"":""Asia"",""country"":""Philippines""}
                                             ]
                              }";

        var result = JsonConvert.DeserializeObject<JsonResult>(jsonString);
        var iranInfo = result.InfoList.Where(i => i.Country.ToString() == "Iran").FirstOrDefault();
    }

    public class JsonResult
    {
        [JsonProperty("results")]
        public List<Info> InfoList { get; set; }
    }

    public class Info
    {
        public object Continent { get; set; }
        public object Country { get; set; }
    }

UPDATE: USING INDEX
As long as the structure of the JSON is consistent always then this kind of sample solution can give you hint.

Console.WriteLine("Original JSON:");
        Console.WriteLine(jsonString);
        Console.WriteLine();

        Console.WriteLine("Step1: Make the json as single line,");
        jsonString = jsonString.Replace(" ", "").Replace(Environment.NewLine, " ");
        Console.WriteLine(jsonString);
        Console.WriteLine();

        Console.WriteLine("Step2: Get index of country Iran. And use that index to get the below output using substring.");
        var iranIndex = jsonString.ToLower().IndexOf(@"""country"":""iran""");
        var iranInitialInfo = jsonString.Substring(iranIndex);
        Console.WriteLine(iranInitialInfo);
        Console.WriteLine();

        Console.WriteLine("Step3: Get inedx of continent. And use that index to get below output using substring.");
        var continentIndex = iranInitialInfo.IndexOf(@"""continent"":");
        iranInitialInfo = iranInitialInfo.Substring(0, continentIndex-3);
        Console.WriteLine(iranInitialInfo);
        Console.WriteLine();

        Console.WriteLine("Step4: Get the first part of the info by using. And combine it with the initialInfo to bring the output below.");
        var beginningIranInfo = jsonString.Substring(0, iranIndex);
        var lastOpenCurlyBraceIndex = beginningIranInfo.LastIndexOf("{");
        beginningIranInfo = beginningIranInfo.Substring(lastOpenCurlyBraceIndex);
        var iranInfo = beginningIranInfo + iranInitialInfo;
        Console.WriteLine(iranInfo);

OUTPUT USING INDEX:
enter image description here

tontonsevilla
  • 2,649
  • 1
  • 11
  • 18