Search code examples
c#visual-studiohttpclient

Error reading JObject from JsonReader. Path '', line 0, position 0.”


I am using the following code to call a post interface in Visual Studio 2022:

private List<Token> LoginToken(string username, string password)
{
 string api = "";
 List<Token> list = new List<Token>();
 string url = "";
 Dictionary<string, string> dics = new Dictionary<string, string>
 {
   { "username", username },
   { "password", password },
   { "loginType", "account" },
   { "grantType", "password" }
 };
 Task<string> task = Api.InvokeWebapi(url, api, "POST", dics);
 string result = task.Result;

 if (result != null)
 {
     JObject jsonObj = null;
     jsonObj = JObject.Parse(result);
     DataInfo info = new DataInfo();
     info.statusCode = Convert.ToInt32(jsonObj["code"]);
     info.message = jsonObj["message"].ToString();
     if (info.statusCode == 1)
     {
         JArray jlist = JArray.Parse(jsonObj["data"].ToString());
         for (int i = 0; i < jlist.Count; ++i)
         {
             Token ver = new Token();
             JObject tempo = JObject.Parse(jlist[i].ToString());
             ver.access_token = tempo["access_token"].ToString();
             ver.token_type = tempo["token_type"].ToString();
             ver.expires_in = Convert.ToInt32(tempo["expires_in"]);
             ver.scope = tempo["scope"].ToString();
             ver.name = tempo["name"].ToString();
             ver.my_Corp = tempo["my_Corp-Code"].ToString();
             ver.userId = Convert.ToInt32(tempo["userId"]);
             ver.username = tempo["username"].ToString();
             ver.jti = tempo["jti"].ToString();
             list.Add(ver);
         }
     }
 }
 return list;
}


public async Task<string> InvokeWebapi(string url, string api, string type, Dictionary<string, string> dics)
{
    string result = string.Empty;
    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Add("Authorization", "Basic 1111");
    client.BaseAddress = new Uri(url);

    client.Timeout = TimeSpan.FromSeconds(510);

    if (type.ToLower() == "put")
    {
        HttpResponseMessage response;
        if (dics.Keys.Contains("input"))
        {
            if (dics != null)
            {
                foreach (var item in dics.Keys)
                {
                    api = api.Replace(item, dics[item]).Replace("{", "").Replace("}", "");
                }
            }
            var contents = new StringContent(dics["input"], Encoding.UTF8, "application/json");
            response = client.PutAsync(api, contents).Result;
            if (response.IsSuccessStatusCode)
            {
                result = await response.Content.ReadAsStringAsync();
                return result;
            }
            return result;
        }

        var content = new FormUrlEncodedContent(dics);
        response = client.PutAsync(api, content).Result;
        if (response.IsSuccessStatusCode)
        {
            result = await response.Content.ReadAsStringAsync();
            return result;
        }
    }
    else if (type.ToLower() == "post")
    {
        var content = new FormUrlEncodedContent(dics);

        HttpResponseMessage response = client.PostAsync(api, content).Result;
        if (response.IsSuccessStatusCode)
        {
            result = await response.Content.ReadAsStringAsync();
            return result;
        }
    }
    else if (type.ToLower() == "get")
    {
        HttpResponseMessage response = client.GetAsync(api).Result;

        if (response.IsSuccessStatusCode)
        {
            result = await response.Content.ReadAsStringAsync();
            return result;
        }
    }
    else
    {
        return result;
    }
    return result;
}
}

I am using the above code to call a post interface in Visual Studio 2022, but the error reported in jsonObj = JObject.Parse(result); is Newtonsoft.Json.JsonReaderException: "Error reading JObject from JsonReader. Path '', line 0, position 0."

Update:

I captured the response of the api when the error was reported:

{StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Pragma: no-cache
X-Frame-Options: DENY
Referrer-Policy: no-referrer
Cache-Control: no-store, must-revalidate, no-cache, max-age=0
Date: Wed, 17 Jul 2024 08:47:38 GMT
Server: nginx/1.24.0
Content-Type: application/json
Expires: 0
}}

Solution

  • Thanks to Panagiotis Kanavos and everyone for their suggestions for improvement. I will study them carefully later. My problem has been solved. The problem was that the format of SerializeObject(dics) was incorrect. I converted it later and it can run successfully.

    var json = JsonConvert.SerializeObject(dics);
    var content = new StringContent(json, Encoding.UTF8, "application/json");
    //var content = new FormUrlEncodedContent(dics);   Previous code