Home > Net >  System.FormatException: 'Input string was not in a correct format.' C# console application
System.FormatException: 'Input string was not in a correct format.' C# console application

Time:02-18

I know this question get all of downvotes, but hey, this is where I am stuck, My scenario, I am trying to get the most 10 active users from this api jsonmock. I have implemented a similar working solution in java and it works well so I decided to give it a short in C#

I don't understand why int totalPages = Integer.MAX_VALUE; this would work perfectly in java and throw an error in C# when I do it like this int totalPages = int.MaxValue; and get the error above '

Input string was not in a correct format.'

this is where am getting the error

                totalPages = int.Parse(response.Substring(49, 50));

I want to extract 10 usernames and print them to the console like from the json

epaga
panny
olalonde
WisNorCan
dmmalam
replicatorblog
vladikoff
mpweiher
coloneltcb
guelo

this is what I have done so far

class Program
    {
        public class GetMostActiveUsers
        {

            public static List<string> getUsernames(int threshold)
            {

                List<string> result = new List<string>();
                int startPage = 1;
                int totalPages = int.MaxValue;
                string subCount = "submission_count";
                string user = "username";
                int currentUserData;
                while (startPage <= totalPages)
                {
                    string url = "https://jsonmock.hackerrank.com/api/article_users?page="   startPage;
                    //HttpClient is also an option here!
                    WebRequest myReq = WebRequest.Create(url);
                    WebResponse wr = myReq.GetResponse();
                    Stream receiveStream = wr.GetResponseStream();
                    StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                    string response = reader.ReadToEnd();

                    //At this point there are many ways to go about this!
                    //you can deserialize to an object,
                    while(response != null)
                    {
                        totalPages = int.Parse(response.Substring(49, 50));
                        List<string> userTitles = getUserTitles(response, user);
                        int count = 0;

                        int index = 0;
                        while (index != -1)
                        {
                            index = response.IndexOf(subCount, index);
                            if (index != -1)
                            {
                                int cc = response.IndexOf(",", index);
                                currentUserData = Int32.Parse(response.Substring(index   subCount.Length   2, cc));
                                if (currentUserData >= threshold)
                                {
                                    result.Add(userTitles[count].Replace("^\"|\"$", ""));//Not sure if this is how to access it
                                }
                                index  ;
                                count  ;
                            }
                        }

                    }
                   
                    startPage  ;
                }

                return result;
            }

    }

            public static List<string> getUserTitles(string response, string user)
            {
                List<string> result = new List<string>();
                int index = 0;
                while (index != -1)
                {
                    index = response.IndexOf(user, index);
                    if (index != -1)
                    {
                        int cc = response.IndexOf(",", index);
                        result.Add(response.Substring(index   user.Length   2, cc));
                        index  ;
                    }
                }
                return result;
            }

            private static void printActiveUsers(List<String> activeUserList)
            {
                foreach (String title in activeUserList)
                {
                    Console.WriteLine(title);
                }

            }

            static void Main(string[] args)
            {
                printActiveUsers(GetMostActiveUsers.getUsernames(10));
            }
        }

How can I see the light and understand what I am wrong?

CodePudding user response:

The problem indeed is in this line of code:

totalPages = int.Parse(response.Substring(49, 50));

Second parameter of .Substring(Int32,Int32) is length (see this doc), i.e., you are trying to read a 50-digit number that starts at position 49. A 50 digit number would not fit into an int unless it's something like 00...00123 (not sure that int.Parse will be ok with that too, tbh, but I'm not going to check).

What you probably wanted to do was .Substring(49, 1) or .Substring(49, 2) (depending on whether you want to read one or two digits).

But generally, considering that you are trying to parse JSON, you should just use a JSON parser library (e.g. Json.NET). Otherwise you are relying on many things to be unchanged that might get changed, such as formatting of the json response, order of the fields in the json response – all required for your total pages number to start at exactly 49th character.

CodePudding user response:

see your code result.

Console.WriteLine(string.Format("{0}", response.Substring(49, 50)));

--> 2,"data":[{"id":1,"username":"epaga","about":"Java

so .. can't parsing to int.

  •  Tags:  
  • c#
  • Related