DeserializeObject is VB and c#

frutuopa

Member
Joined
Apr 4, 2022
Messages
6
Programming Experience
10+
Hello
When I try to consume an API in VB and C# the results are different. Look at the results.... in VB double quotes appear and in C# it appears \"...
Is it just a representation problem?
I need to get this out of the way because I can't figure out why the rest of the code doesn't work in VB.

Thanks

VB.NET
Dim model As ConsumosModel = New ConsumosModel()
Dim modelResponse As ConsumoResponseModel = New ConsumoResponseModel()

model.CodigoExternoSeccao = txtCodigoExternoSeccao.Text
model.DataInicio = dtpapi1.Value
model.DataFim = dtpapi2.Value
Dim json As String = JsonConvert.SerializeObject(model)
Dim content As HttpContent = New StringContent(json, Encoding.UTF8, "application/json")
Dim response = Await client.PostAsync(txturl.Text & "Fecho/GetInfoConsumos", content)
Dim responseString = response.Content.ReadAsStringAsync()

Dim resposta As FitApiListResponse(Of ConsumoResponseModel) = JsonConvert.DeserializeObject(Of FitApiListResponse(Of ConsumoResponseModel))(responseString.Result)

?responseString.Result
"{""model"":[{""formaPagamento"":""CRÉDITO"",""tipoPagamento"":""Credito"",""nomePerfil"":""Colaboradores"",




C#
ConsumosModel model = new ConsumosModel();
model.CodigoExternoSeccao = txtCodigoExternoSeccao.Text;
model.DataInicio = dateTimePicker1.Value.Date;
model.DataFim = dateTimePicker2.Value.Date;
string json = JsonConvert.SerializeObject(model);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");

var response = await client.PostAsync(this.txtUrl.Text + "Fecho/GetInfoConsumos", content);

var responseString = response.Content.ReadAsStringAsync();

FitApiListResponse<ConsumoResponseModel> resposta = JsonConvert.DeserializeObject<FitApiListResponse<ConsumoResponseModel>>(responseString.Result);



?responseString.Result
"{\"model\":[{\"formaPagamento\":\"CRÉDITO\",\"tipoPagamento\":\"Credito\",\"nomePerfil\":\"Colaboradores\",\"livre\":\"COLABORADORES\",
 
No, the results are not different. That's just how double-quotes are represented in literal strings in the two languages. Double-quotes are the delimiters for literal strings so they need to be escaped within the string itself. VB does that with another double-quote, e.g.
VB.NET:
Dim str = "He said ""Hello"" to me."
and C# does it with backslashes, e.g.
C#:
var str = "He said \"Hello\" to me.";
Those two code snippets produce exactly the same text. That's all you're seeing. If you actually output that text to the console, a file or a text box or whatever, you'll see that.
 
Thank you for your answer...

I'm going to take the opportunity to resolve this definitively.

Below I show the code associated with a button and the corresponding class.

resposta.Success is always False.... In the last sub I show you, in the constructor, in debug mode, I can see that the list is well filled, and that Succes=true and message="OK"... However, it is continuous giving the error
As I said in the previous post, if i run the compatible version in C#, everything goes well
Thank you very much

====================================== clgertal.vb

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.IO
Imports System.Text


Namespace pf


Public Class clGertal


Public Class parametros
Public Property url As String
Public Property ApiKey As String
Public Property Key As String
Public Property CodigoExternoSeccao As String
End Class

Public Class ConsumosModel

Public Property CodigoExternoSeccao As String
Public Property DataInicio As DateTime
Public Property DataFim As DateTime
End Class

Public Class ConsumoResponseModel
Public Property FormaPagamento As String
Public Property TipoPagamento As String
Public Property NomePerfil As String
Public Property Livre As String
Public Property CodigoExternoConsumidor As String
Public Property Nome As String
Public Property CentroCusto As String
Public Property Data As String
Public Property NomeRefeicao As String
Public Property Hora As String
Public Property NumeroDocumento As String
Public Property NomeFamiliaProduto As String
Public Property CodigoExternoProduto As String
Public Property NomeProduto As String
Public Property Quantidade As Decimal
Public Property Preco As Decimal
Public Property PrecoFatura As Decimal
Public Property Valor As Decimal
Public Property Faltoso As String
Public Property NumeroCartao As String
Public Property ERefeicao As String
Public Property NumeroSeriePos As String
End Class
Public Class ConsumidorModel
Public Property CodigoExternoSeccao As String
Public Property NumeroColaborador As String
Public Property Nome As String
Public Property Cartao1 As String
Public Property CCusto As String
Public Property CodigoExternoPerfil As String
Public Property Telemovel As String
Public Property Email As String
Public Property NIF As String
Public Property Livre As String
End Class

Public Class ConsumidoresResponseModel
Public Property NumeroColaborador As String
Public Property Estado As String
Public Property Mensagem As String
End Class

Public Class FitApiListResponse
Public Const OkMessage As String = "Ok"
Public Const FailMessage As String = "Fail"
Public Property Success As Boolean
Public Property Message As String

Public Sub New(ByVal success As Boolean, ByVal message As String)
success = success
message = message
End Sub

Public Shared Function Ok(Of T)(ByVal model As List(Of T)) As FitApiListResponse(Of T)
Return FitApiListResponse(Of T).Ok(model)
End Function

Public Shared Function Ok(Of T)(ByVal model As IEnumerable(Of T)) As FitApiListResponse(Of T)
Return FitApiListResponse(Of T).Ok(model)
End Function

Public Shared Function Ok(Of T)(ByVal model As List(Of T), ByVal message As String) As FitApiListResponse(Of T)
Return FitApiListResponse(Of T).Ok(model, message)
End Function

Public Shared Function Ok(Of T)(ByVal model As IEnumerable(Of T), ByVal message As String) As FitApiListResponse(Of T)
Return FitApiListResponse(Of T).Ok(model, message)
End Function

Public Shared Function Fail(Of T)(ByVal message As String) As FitApiListResponse(Of T)
Return New FitApiListResponse(Of T)(Nothing, message, False)
End Function

Public Shared Function Fail(Of T)(ByVal model As List(Of T)) As FitApiListResponse(Of T)
Return FitApiListResponse(Of T).Fail(model)
End Function

Public Shared Function Fail(Of T)(ByVal model As IEnumerable(Of T)) As FitApiListResponse(Of T)
Return FitApiListResponse(Of T).Fail(model)
End Function

Public Shared Function Fail(Of T)(ByVal model As List(Of T), ByVal message As String) As FitApiListResponse(Of T)
Return FitApiListResponse(Of T).Fail(model, message)
End Function

Public Shared Function Fail(Of T)(ByVal model As IEnumerable(Of T), ByVal message As String) As FitApiListResponse(Of T)
Return FitApiListResponse(Of T).Fail(model, message)
End Function
End Class


Public Class FitApiListResponse(Of T)
Inherits FitApiListResponse

Public Property Model As List(Of T)

Public Sub New(ByVal model As List(Of T), ByVal message As String, ByVal success As Boolean)
MyBase.New(success, message)
model = model
success = success
message = message
End Sub

Public Overloads Shared Function Ok(ByVal model As List(Of T)) As FitApiListResponse(Of T)
Return New FitApiListResponse(Of T)(model, OkMessage, True)
End Function

'
Public Overloads Shared Function Ok(ByVal model As IEnumerable(Of T)) As FitApiListResponse(Of T)
Return Ok(model.ToList())
End Function

Public Overloads Shared Function Ok(ByVal model As List(Of T), ByVal message As String) As FitApiListResponse(Of T)
Return New FitApiListResponse(Of T)(model, message, True)
End Function

Public Overloads Shared Function Ok(ByVal model As IEnumerable(Of T), ByVal message As String) As FitApiListResponse(Of T)
Return Ok(model.ToList(), message)
End Function

Public Overloads Shared Function Fail(ByVal message As String) As FitApiListResponse(Of T)
Return New FitApiListResponse(Of T)(Nothing, message, False)
End Function

Public Overloads Shared Function Fail(ByVal model As List(Of T)) As FitApiListResponse(Of T)
Return New FitApiListResponse(Of T)(model, FailMessage, False)
End Function

Public Overloads Shared Function Fail(ByVal model As IEnumerable(Of T)) As FitApiListResponse(Of T)
Return Fail(model.ToList())
End Function

Public Overloads Shared Function Fail(ByVal model As List(Of T), ByVal message As String) As FitApiListResponse(Of T)
Return New FitApiListResponse(Of T)(model, message, False)
End Function

Public Overloads Shared Function Fail(ByVal model As IEnumerable(Of T), ByVal message As String) As FitApiListResponse(Of T)
Return Fail(model.ToList(), message)
End Function
End Class



End Class
Public Module SystemIo

Public Function GetParametros() As clGertal.parametros
Dim param As clGertal.parametros = New clGertal.parametros()

Try
Dim dados As String = LerDados("parametros.json")
param = JsonConvert.DeserializeObject(Of clGertal.parametros)(dados)
Catch ex As Exception
MessageBox.Show(ex.Message, "Erro")
End Try

Return param
End Function
Public Function LerDados(ByVal path As String) As String
Dim retVal As String = ""

Try

If Not System.IO.Directory.Exists("Files") Then
System.IO.Directory.CreateDirectory("Files")
End If

Dim file As String = "Files\" & path

If Not System.IO.File.Exists(file) Then
Return retVal
End If

Using sr As StreamReader = System.IO.File.OpenText(file)
Dim s As String = ""

While (CSharpImpl.__Assign(s, sr.ReadLine())) IsNot Nothing
retVal = retVal & s
End While
End Using

Catch ex As System.Exception
MessageBox.Show(ex.Message, "Erro")
End Try

Return retVal
End Function

Private Class CSharpImpl
<Obsolete("Please refactor calling code to use normal Visual Basic assignment")>
Shared Function __Assign(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
End Class

Public Sub GuardarDados(ByVal path As String, ByVal dados As String)
Try

If Not System.IO.Directory.Exists("Files") Then
System.IO.Directory.CreateDirectory("Files")
End If

Dim file As String = "Files\" & path

If System.IO.File.Exists(file) Then
System.IO.File.Delete(file)
End If

If Not System.IO.File.Exists(file) Then

Using sw As StreamWriter = System.IO.File.CreateText(file)
sw.Write(dados)
End Using
End If

Catch ex As System.Exception
MessageBox.Show(ex.Message, "Erro")
End Try
End Sub

End Module
End Namespace

===========================================
Private Async Sub btnGetInfoConsumos_Click(sender As Object, e As EventArgs) Handles btnGetInfoConsumos.Click

Dim url As String = txturl.Text
Dim TRNApiKey As String = txtApiKey.Text '

Dim client As HttpClient = New HttpClient()
client.DefaultRequestHeaders.Accept.Clear()
client.DefaultRequestHeaders.Add("APIkey", TRNApiKey)
client.DefaultRequestHeaders.Accept.Add(New Headers.MediaTypeWithQualityHeaderValue("application/json"))


Dim model As ConsumosModel = New ConsumosModel()
Dim modelResponse As ConsumoResponseModel = New ConsumoResponseModel()


model.CodigoExternoSeccao = txtCodigoExternoSeccao.Text
model.DataInicio = dtpapi1.Value
model.DataFim = dtpapi2.Value
Dim json As String = JsonConvert.SerializeObject(model)
Dim content As HttpContent = New StringContent(json, Encoding.UTF8, "application/json")
Dim response = Await client.PostAsync(txturl.Text & "Fecho/GetInfoConsumos", content)
Dim responseString = response.Content.ReadAsStringAsync()

Dim resposta As FitApiListResponse(Of ConsumoResponseModel) = JsonConvert.DeserializeObject(Of FitApiListResponse(Of ConsumoResponseModel))(responseString.Result)

If resposta.Success Then
DataGridView2.DataSource = resposta.Model
MessageBox.Show(resposta.Model.Count.ToString() & " linhas", "Sucesso")
Else
DataGridView2.DataSource = Nothing
MessageBox.Show(resposta.Message, "Erro")
End If
End Sub

=====================================

Public Sub New(ByVal model As List(Of T), ByVal message As String, ByVal success As Boolean)
MyBase.New(success, message)
model = model '''' LIST OK
success = success
message = message
End Sub
 
Back
Top