vb.netserializationjson.netusps

Problem deserializing a response from USPS CityStateLookup with Newtonsoft.Json.JsonConvert.DeserializeObject


I'm attempting to parse a response from the USPS CityStateLookup API and I don't appear to be modelling it properly, as I'm getting an "{"Unexpected character encountered while parsing value: <. Path '', line 0, position 0."}" while parsing" error right at the beginning of the DeserializeObject call

My code is:

Class CityStateLookupResponse
    Property ZipCodeList As List(Of ZipCode)
End Class

 Class ZipCode
    Property Zip5 As String
    Property City As String
    Property State As String
 End Class


Private Async Function GetCityStateFromZipAsync(byval Zip5Code as string) as threading.tasks.task(of CityStateLookupResult)

 Dim result As New CityStateLookupResponse

 Dim client As New HttpClient() With {
        .BaseAddress = New Uri("http://production.shippingapis.com/ShippingAPI.dll")
    }

    Dim arguments As String = "?API=CityStateLookup&XML=<CityStateLookupRequest USERID=""{0}""><ZipCode ID= ""{1}""><Zip5>{2}</Zip5></ZipCode></CityStateLookupRequest>"
    arguments = String.Format(arguments, "<My User ID>", 0, Zip5Code)

    response = Await client.GetAsync(arguments)

    If Not response.IsSuccessStatusCode Then
        Return result
    End If

    myContent = Await response.Content.ReadAsStringAsync

    ' vvvv  THIS IS THE ERROR LINE  vvvv
    result = Newtonsoft.Json.JsonConvert.DeserializeObject(Of CityStateLookupResponse)(myContent) 
end function

The returned XML for the same API call in a browser is:

<CityStateLookupResponse>
    <ZipCode ID="0">
        <Zip5>55016</Zip5>
        <City>COTTAGE GROVE</City>
        <State>MN</State>
     </ZipCode>
 </CityStateLookupResponse>

What am I doing wrong in the class definition for CityStateLookupResponse? (Or is there a better way to go about this altogether?)


Solution

  • Haven't looked at VB in a while but it appears you are using the wrong method for deserializing XML. The method you are using is meant for JSON.

    For XML deserialization use DeserializeXmlNode.