使用 Newtonsoft.Json.JsonConvert.DeserializeObject 反序列化来自 USPS CityStateLookup 的响应时出现问题

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

我正在尝试解析来自 USPS CityStateLookup API 的响应,但我似乎没有正确建模,因为我收到“{"Unexpected character encountered while parsing value: <. Path '', line 0, position 0."}”解析”错误就在 DeserializeObject 调用的开头

我的代码是:

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

浏览器中相同 API 调用返回的 XML 是:

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

我在 CityStateLookupResponse 的 class 定义中做错了什么? (或者有更好的方法来解决这个问题吗?)

有一段时间没有查看 VB,但您似乎使用了错误的反序列化方法 XML。您使用的方法适用于 JSON.

对于 XML 反序列化使用 DeserializeXmlNode.