Home > Software engineering >  text.json deserialize i get a error c# conversion error
text.json deserialize i get a error c# conversion error

Time:12-15

I am pulling data from API. I am getting an error while deserializing. please help me.

error:

System.Text.Json.JsonException: '',' is invalid after a single JSON value. Expected end of data. Path: $ | LineNumber: 0 | BytePositionInLine: 128.'

data i pull:

{"firmano":128257,"adi":"- FATİH YILMAZ"},{"firmano":128446,"adi":"-MEHMET ÜSTÜN"}

my c# codes:

Index.cs :

 var result = await Api<Company>.pullDataAsync("https://localhost:5001/api/PesinIskontolar/companyGet");

api.cs:

 public class Api<T> where T : class
    {
        public async static Task<T> pullDataAsync(string url)
        {
            var client = new RestClient(url);
            var request = new RestRequest(Method.GET);
            IRestResponse response = await client.ExecuteAsync(request);

            return Json_Convert<T>.deserializeProcess(apiFormat(response.Content));
        }

        public static string apiFormat(string response)
        {          
            var result = response.Replace("\\", "").Replace("[","").Replace("]","");
            return result.Substring(1, result.Length - 2);
        }

        
    }

Json_Convert.cs:

public class Json_Convert<T> where T : class
    {
        public static T deserializeProcess(string response)
        {
            return JsonSerializer.Deserialize<T>(response);
        }

    }

dal:

public string getCompany()
        {
......
    DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
    
                da.Fill(dt);
    
                string data = JsonConvert.SerializeObject(dt);
    
                baglanti.Close();
                baglanti.Dispose();
   return data;
        }

api:

[HttpGet("companyGet")]
        public IActionResult companyGet()
        {
            return Ok(_firmaServices.getCompany());
        }

Since some friends said that there is a problem with the api, I added other codes.

company class:

public class Company
    {
        public int firmano { get; set; }
        public string adi { get; set; }
    }

CodePudding user response:

Your JSON is invalid, should be:

[{"firmano":128257,"adi":"- FATİH YILMAZ"},{"firmano":128446,"adi":"-MEHMET ÜSTÜN"}]

instead of:

{"firmano":128257,"adi":"- FATİH YILMAZ"},{"firmano":128446,"adi":"-MEHMET ÜSTÜN"}

Also, instead of calling response.Content prior to deserialization, you need to call await response.Content.ReadAsStringAsync() method to actually read the returning json string from the server.

As you pulling a list of two companies, your deserialization should be deserializing to a list instead of a single object, so you need to delete the apiFormat method and call await Api<IEnumerable<Company>>.pullDataAsync instead of await Api<Company>.pullDataAsync

CodePudding user response:

You should deserialize List< Company >, not just Company so use this code

var result = await Api<List<Company>>.pullDataAsync("https://localhost:5001/api/PesinIskontolar/companyGet");

and fix your generic code by removing apiFormat(response.Content), replace it by just content. it will prevent removing [] from your json, this is what causes an exception

         public async static Task<T> pullDataAsync(string url)
        {
            var client = new RestClient(url);
            var request = new RestRequest(Method.GET);
            IRestResponse response = await client.ExecuteAsync(request);

            return Json_Convert<T>.deserializeProcess(response.Content); //fix here!!!
        }

and according to your response.Content, you company class should be changed

public partial class Company
    {
        [JsonPropertyName("firmano")]
        public int firmano { get; set; }

        [JsonPropertyName("Column1")]
        public string adi { get; set; }
    }

CodePudding user response:

1.Try to use known class as Company instate of 2.Json converter does not like special characters like '(Some times People are using the ' char, to write a letter like è, and this can bracke the Json String). You can do like .Replace("'", "''")
3.Use encoding UTF8. 4.Control the API Site in Debug and see the Response creation.. 5. before subtracting the end 2 chars check if the string has this chars. better do this operations after you get the response. return result.Substring(1, result.Length - 2);

  • Related