我正在从一个外部合作伙伴那里读取一个JSON文件,该文件并不完全一致(他们不会很快更改它(。
我想检查字段bathroom
的值,并将其存储在一个整数中。这里有一个潜在价值的映射,我想得到:
"" = 0
= 0 (here no value is present)
2 = 2
"2" = 2
但无论我尝试什么(见下文(,我都会得到错误:
输入字符串的格式不正确。
Dim json as string = "[{""bathrooms"": """"}, {""bathrooms"": }, {""bathrooms"": 2},{""bathrooms"": ""1""}]"
Dim iBathrooms As Integer
Dim jsonArray As Newtonsoft.Json.Linq.JArray = JArray.Parse(json)
For Each item In jsonArray
iBathrooms= If(item.Value(Of Integer?)("bathrooms"), 0)
iBathrooms = If(CType(item("bathrooms"), Integer?), 0)
Int32.TryParse(item("bathrooms").Value(Of Integer).ToString, iBathrooms)
Next
我已经在这里检查过:从可能不存在的JToken中获取价值(最佳实践(
如果JSON的问题始终是缺少值,那么可以插入一个空字符串:
Dim json As String = "[{""bathrooms"": """"}, {""bathrooms"": }, {""bathrooms"": 2},{""bathrooms"": ""1""}]"
Dim re = New Text.RegularExpressions.Regex(":s*}")
Dim json2 = re.Replace(json, ": """"}")
Console.WriteLine(json2)
输出:
[{"bathrooms": ""}, {"bathrooms": ""}, {"bathrooms": 2},{"bathrooms": "1"}]
这是有效的JSON。
然后您可以检查该值是否可以解析为整数:
Dim json As String = "[{""bathrooms"": """"}, {""bathrooms"": """"}, {""bathrooms"": 2},{""bathrooms"": ""1""}]"
Dim re = New Text.RegularExpressions.Regex(":s*}")
json = re.Replace(json, ": """"}")
Dim nBathrooms As Integer
Dim jsonArray As Newtonsoft.Json.Linq.JArray = JArray.Parse(json)
For Each item In jsonArray
Dim q = item("bathrooms")
If q IsNot Nothing AndAlso Integer.TryParse(q.Value(Of Object).ToString(), nBathrooms) Then
Console.WriteLine(nBathrooms)
Else
Console.WriteLine("Not specified.")
End If
Next