Error passing JSON to API

Fábio Freitas 0 Reputation points
2023-11-10T15:43:14.5866667+00:00
I'm transforming a vb.net class into a JsonSerializer.Serialize and after trying to integrate with an APi it presents an error not finding the client.

I did a test and went straight to HttpRequestMessage

  request.Content = New StringContent("{""contractor"":{""numero"":""015380"",""tipo"":2}") with two quotes and it worked, but with just one quote like serialized does not find the contrinuent.

Any suggestion?
Thank you very much in advance.
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,480 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
335 questions
{count} votes

2 answers

Sort by: Most helpful
  1. ChandraHundigamVenkat 11 Reputation points
    2023-11-10T16:19:48+00:00

    The problem might be due to the way you’re serializing your data. When you manually create a JSON string with double quotes ("{""contractor"":{""numero"":""015380"",""tipo"":2}"), it works fine. However, when you use JsonSerializer.Serialize, which uses single quotes, it doesn’t work.

    Try with single quotes.

    0 comments No comments

  2. Fábio Freitas 0 Reputation points
    2023-11-10T16:47:03.22+00:00
            Dim NovasMensagens As New EntradaIndicadorNovasMensagens()
    
            NovasMensagens.contratante = New Contratante() With {
                .numero = 123456789,
                .tipo = 2
            }
    
            Dim jsonString As String = JsonSerializer.Serialize(NovasMensagens)
    
            Using httpClient = New HttpClient()
                Using request As New HttpRequestMessage(HttpMethod.Post, URLBASE & "Monitorar")
                    request.Headers.TryAddWithoutValidation("accept", "*/*")
                    request.Headers.TryAddWithoutValidation("jwt_token", JWK_Token)
                    request.Headers.TryAddWithoutValidation("Authorization", "Bearer " & Acesss_Token)
                    request.Headers.TryAddWithoutValidation("Content-Type", "application/json")
    
                    Dim stringContent As New StringContent(jsonString, Encoding.UTF8, "application/json")
    
                    Dim response As Task(Of HttpResponseMessage) = httpClient.SendAsync(request)
    
                    Return Await response.Result.Content.ReadFromJsonAsync(Of RetornoIndicadorNovasMensagens)(OpcoesDesserializarJson)
    
                End Using
            End Using
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.