我正在從一個不完全一致的外部合作伙伴那里讀取一個 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 中獲取價值(最佳實踐)
uj5u.com熱心網友回復:
如果 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/442640.html
