I have this JSON, which is valid according to JSONbeautify.com :
{
"date_check": "2023-04-05",
"updated_datas": [
{
"FIELD_NAME": "BLN_ADS_LINKS_DETECTED",
"NEW_VALUE": false,
"OLD_VALUE": true
},
{
"FIELD_NAME": "ADS_LINKS_DETECTED",
"NEW_VALUE": null,
"OLD_VALUE": "?"
}
]
}
I’d like to display it in a datatable.
I use this function:
Public Function JsonStringToDataTable(ByVal json As String) As DataTable
Dim jsonLinq = JObject.Parse(json)
Dim srcArray = jsonLinq.Descendants().Where(Function(d) TypeOf d Is JArray).First()
Dim trgArray = New JArray()
For Each row As JObject In srcArray.Children(Of JObject)()
Dim cleanRow = New JObject()
For Each column As JProperty In row.Properties()
If TypeOf column.Value Is JValue Then
cleanRow.Add(column.Name, column.Value)
End If
Next
trgArray.Add(cleanRow)
Next
Return JsonConvert.DeserializeObject(Of DataTable)(trgArray.ToString(), New JsonSerializerSettings With {.NullValueHandling = NullValueHandling.Ignore})
End Function
I got this exception:
Error converting value "?" to type 'System.Boolean'. Path '[1].OLD_VALUE', line 10, position 20.
I don’t understand: why a boolean?
2
Answers
Json.NET will use the first row to determine the datatype for column, so it will process
OLD_VALUE
as bool for this input json. Since you are already processing json manually you can try forcing all data being strings. Not fluent with VB but here is working snippet in C# to give you the idea (main idea is to useToString
on prop value when adding it to the new object –row.Add(prop.Name, prop.Value.ToString())
, but there is some other stuff also):Or you can create custom
DataTableConverter
which will infer correct type, like in this answerthe easiest way to fix json would be to use a string replacement
also try this instead of your tonns of code