Reputation: 63
I am trying to parse the following data returned in JSON
{
"Id":8151302,
"Status":"Accepted",
"Response":"0",
"Price":"0.88",
"Detail":"https://api.test.com/Redirect/Index 3eae1b02"
}
This is what I have tried using:
sresult = sresult.Replace("""""", String.Empty)
If sresult.Contains("Status"":""Accepted") Then
Dim parts = sresult.Replace("{", String.Empty).Replace("}", String.Empty).Split(",")
For i As Int16 = 0 To parts.Length - 1
If parts(i).StartsWith("Detail"":") Then
app.Outcome.RedirectURL = parts(i).Substring(12)
End If
If parts(i).StartsWith("Price"":") Then
lendertier.LenderComm = CDec(parts(i).Substring(11))
End If
If parts(i).StartsWith("Id") Then
app.Outcome.LenderReference = parts(i).Substring(15)
End If
Next
AcceptLead()
Return True
The returned results I get after parsing are
URL:
REF:
PRICE:£0.00
And it should be:
URL: https://api.test.com/Redirect/Index 3eae1b02
ID: 8151302
PRICE: 0.88
I tried deserializing it as well. I get the same results:
Dim sReason As String = "Unknown"
Dim JSON As JavaScriptSerializer = New JavaScriptSerializer()
Dim SH As SandhurstData = JSON.Deserialize(Of SandhurstData)(sResult)
If SH.Status = "Accepted" Then
app.Outcome.RedirectURL = SH.RedirectURL
app.Outcome.LenderReference = SH.ApplicationRef
lendertier.LenderComm = SH.Commission
AcceptLead()
Return True
End If
sReason = SH.Reason
If Not SH.ValidationErrors Is Nothing Then
If (SH.ValidationErrors.Count > 0) Then
For Each e As String In SH.ValidationErrors
sReason &= e + "; "
Next
End If
End If
DeclineLead(sReason.Trim())
Return False
End Function
<Serializable> _
Public Class SandhurstData
Public Property Status() As String
Public Property RedirectURL() As String
Public Property Commission() As Decimal
Public Property ApplicationRef As String
Public Property ValidationErrors As List(Of String)
Public Property Reason As String
End Class
Upvotes: 2
Views: 481
Reputation: 53610
As the comments have mentioned, JSON.NET is the way to go. It's super easy to do:
Public Sub Main()
Dim json as String = "{'Id':'8151302', 'Status':'Accepted', 'Response':'0', 'Price':'0.88', 'Detail':'https://api.test.com/Redirect/Index 3eae1b02'}"
Dim deserialized = JsonConvert.DeserializeObject(of SandhurstData)(json)
Console.WriteLine(deserialized)
End Sub
Public Class SandhurstData
Public Id as String
Public Status as String
Public Response as String
Public Price as Double
Public Detail as String
Public Overrides Function ToString() as String
return String.Format("Id: {1} {0}Status: {2} {0}Response: {3} {0}Price: {4} {0}Detail: {5}", Environment.NewLine, Id, Status, Response, Price, Detail)
End Function
End Class
If the DeserializeObject
method throws errors, it's likely because your JSON is invalid or does not match the target object.
Example fiddle: here
Upvotes: 2