0

I am a fairly new programmer and I'm trying to build an app in Xamarin Forms with C#. I am following a tutorial series from YouTube very closely (https://www.youtube.com/playlist?list=PLV916idiqLvcKS1JY3S3jHWx9ELGJ1cJB). I am using Visual Studio 2019, but the tutorial was made with Visual Studio 2017.

I have now finished my login screen and I am trying to move on to the next page in the app. The login screen runs just fine, but as soon as I hit the "Sign in"-button I get the following error:

Newtonsoft.Json.JsonReaderExeption: 'Unexpected character encountered while parsing value: <. Path ", line 0, position 0.'

It seems as though the problem lies within the exchange of data between the app and the database, although - as I'm very new to this - I'm not too sure.

Here are some links to possible solutions I have found so far:

Unexpected character encountered while parsing value,

jsonreaderexception unexpected character encountered,

https://social.msdn.microsoft.com/Forums/vstudio/de-DE/765784e3-abbd-4b14-a57c-81cdd3ad99ac/unexpected-character-encountered-while-parsing-value-lt-path-line-0-position-0?forum=csharpgeneral,

https://github.com/docusign/docusign-csharp-client/issues/72,

https://www.codeproject.com/Questions/1227147/Unexpected-character-encountered-while-parsing-val,

https://help.octopus.com/t/error-unexpected-character-encountered-while-parsing-value-path-line-0-position-0/4121.

I have found some more, but I can't seem to be able to apply their solutions to my code either. Speaking of which - here it is:

public RestService()
        {
            client = new HttpClient();
            client.MaxResponseContentBufferSize = 256000;
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
        }

        public async Task<Token> Login(User user)
        {
            var postData = new List<KeyValuePair<string, string>>();
            postData.Add(new KeyValuePair<string, string>("grant_type", grant_type));
            postData.Add(new KeyValuePair<string, string>("username", user.Username));
            postData.Add(new KeyValuePair<string, string>("password", user.Password));
            var content = new FormUrlEncodedContent(postData);
            var response = await PostResponseLogin<Token>(Constants.LoginUrl, content);
            DateTime dt = new DateTime();
            dt = DateTime.Today;
            response.expire_date = dt.AddSeconds(response.expire_in);
            return response;
        }

        public async Task<T> PostResponseLogin<T>(string weburl, FormUrlEncodedContent content) where T : class
        {
            var response = await client.PostAsync(weburl, content);
            var jsonResult = response.Content.ReadAsStringAsync().Result;
            var responseObject = JsonConvert.DeserializeObject<T>(jsonResult);
            return responseObject;
        }

        public async Task<T> PostResponse<T>(string weburl, string jsonstring) where T : class
        {
            var Token = App.TokenDatabase.GetToken();
            string ContentType = "application/json";
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Token.access_token);
            try
            {
                var Result = await client.PostAsync(weburl, new StringContent(jsonstring, Encoding.UTF8, ContentType));
                if (Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var JsonResult = Result.Content.ReadAsStringAsync().Result;
                    try
                    {
                        var ContentResp = JsonConvert.DeserializeObject<T>(JsonResult);
                        return ContentResp;
                    }
                    catch { return null; }
                }
            }
            catch { return null; }
            return null;
        }

        public async Task<T> GetResponse<T>(string weburl) where T : class
        {
            var Token = App.TokenDatabase.GetToken();
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Token.access_token);
            try
            {
                var response = await client.GetAsync(weburl);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var JsonResult = response.Content.ReadAsStringAsync().Result;
                    try
                    {
                        var ContentResp = JsonConvert.DeserializeObject<T>(JsonResult);
                        return ContentResp;
                    }
                    catch { return null; }
                }
            }
            catch { return null; }
            return null;
        }

This is the only part in the whole project where json is implemented. I don't know if the error could be coming from another part, but I doubt that.

As I mentioned, I am a pretty new programmer, so it is very hard for me to figure out what's wrong or what I could try.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • The response you get back is likely not what you think. I would suggest making a console app and just running the request and seeing what is coming back – TheGeneral Aug 07 '20 at 08:29
  • Thanks for the quick response @TheGeneral! Do you mean making a seperate project and simply running the code for the database communication? And if so, what needs to come back? – FridolinToGo Aug 07 '20 at 09:00
  • Yeah it seems to be an issue with the json deserialization, i know how hacky xamarin can be.. So to make it easier, i would just put the code into a console app and test it out first. Though would probably need to add the appropriate nugets. The specific code that is doing the json conversion, or where you are getting the json from – TheGeneral Aug 07 '20 at 09:10
  • `var responseObject = JsonConvert.DeserializeObject(jsonResult);` this line is probably choking because your JSON is not valid. You need to examine `jsonResult` to see why. My guess is that it is actually returning HTML, not JSON. – Jason Aug 07 '20 at 12:28
  • Please check the jsonResult to see if it is a vaild json. – nevermore Aug 10 '20 at 02:03
  • Thanks for the suggestion @TheGeneral. I have now verifyed that it is actually returning HTML. What can I do to make it return json? I have again tried to find already existing solutions and none of them have worked. Do I need to add or remove something? Is there something wrong with my request? – FridolinToGo Aug 10 '20 at 07:34
  • It depends how they implemented the call, You need to contact the person who created the webservice, and ask them what is required, or you will need to read the documentation. You could also use a program like Postman to prob it until it works – TheGeneral Aug 10 '20 at 07:36
  • Thanks! I will certainly try that. ;) – FridolinToGo Aug 10 '20 at 07:45
  • You can share your solution here once you solved it:). – nevermore Aug 11 '20 at 06:17
  • Here you go @JackHua-MSFT ;) : The problem was within the url I was targeting. It couldn't give me back json data, so it gave me html... I am now on the lookout for a working online database. Thanks to everyone, all the suggestions were helpful to me! – FridolinToGo Aug 12 '20 at 07:06

0 Answers0