0

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; }
    }
apaderno
  • 28,547
  • 16
  • 75
  • 90
  • 4
    Why are you removing "[" and "]" from your response?' => `var result = response.Replace("\\", "").Replace("[","").Replace("]","");` – Thomas Stachl Dec 14 '21 at 12:47
  • 1
    @ThomasStachl when I didn't remove them in another project it was giving a conversion error. Removing it fixed it. so i used it in this project as well. but it didn't work here – batuhan343434 Dec 14 '21 at 12:49
  • 1
    You shouldn't remove backslashes, either. Fundamentally, you should parse the JSON as it's been provided. Chances are you took the wrong approach in the previous project too... – Jon Skeet Dec 14 '21 at 12:49
  • @JonSkeet ok but now I get an error even if I don't uninstall it. how do i solve it? – batuhan343434 Dec 14 '21 at 12:51
  • 2
    As MestreDosMagros said, you should deserialize to a list instead of to a single result. I'd also *strongly* advise you to start following .NET naming conventions.. – Jon Skeet Dec 14 '21 at 12:53
  • As the allmighty @JonSkeet wrote, don't remove anything from the serialized content. If you removed this part and still encounter an error, rephrase the question to the current problem with updated information or close this qestion and ask a new one – Thomas Stachl Dec 14 '21 at 12:58
  • @ThomasStachl yes. I removed the apiFormat method. While pulling the api, I pulled it as a list, but still the same problem persists. – batuhan343434 Dec 14 '21 at 13:12
  • @batuhan343434 Do you deserialize it like MestreDosMagros wrote to a list? And what error you exactly getting atm – Thomas Stachl Dec 14 '21 at 13:14
  • @ThomasStachl I did as Serge said in the answer below. new error: System.Text.Json.JsonException: 'The JSON value could not be converted to System.Collections.Generic.List`1[winUI.DTO.Company]. Path: $ | LineNumber: 0 | BytePositionInLine: 5006868.' – batuhan343434 Dec 14 '21 at 13:21
  • It's hard to know what that error is without knowing what's at that location. Maybe it's invalid JSON... – Jon Skeet Dec 14 '21 at 14:27

3 Answers3

2

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

MestreDosMagros
  • 1,000
  • 5
  • 19
1

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; }
    }
Serge
  • 40,935
  • 4
  • 18
  • 45
0

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);