Question

I am using JSon.net library to deserialize some objects and it works fine:

Public Class Person
  Public Property PersonId As Long
  Public Property Name As String
  Public Property SSN As Integer
End Class

Dim json = {'Name':'John', 'SSN':'ABC'}

JsonConvert.DeserializeObject(json, GetType(Person))

However, in my case json can contain invalid data (like SSN above) and in that case all I get as error is "Input string was not in a correct format." Is there a way to find out what field exactly provoked the error?

Was it helpful?

Solution

If your JSON is formatted correctly, then Json.Net should report detailed errors if it cannot convert a value. I tried it with the following code using version 5.0.8 (the latest available in NuGet):

Sub Main()
    Dim json As String = "{""Name"":""John"", ""SSN"":""ABC""}"
    JsonConvert.DeserializeObject(json, GetType(Person))
End Sub

Public Class Person
    Public Property PersonId As Long
    Public Property Name As String
    Public Property SSN As Integer
End Class

...and I got a JsonReaderException with the following message text:

Could not convert string to integer: ABC. Path 'SSN', line 1, position 27.

If you're getting Input string was not in a correct format instead, that could mean that something is wrong with your JSON string that is confusing the parser. I notice in your question that you are using single quotes around the property names and values instead of double quotes. That is technically not valid JSON according to the spec (see JSON.org), and may be what is causing the problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top