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

时间:2019-01-26 06:18:14

标签: vb.net serialization json.net usps

我正在尝试分析来自USPS CityStateLookup API的响应,但似乎无法正确建模,因为我在解析值:<时遇到“ {”意外字符。路径”,行0,位置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的类定义中做错了什么? (或者是否有更好的方法可以完全解决这个问题?)

1 个答案:

答案 0 :(得分:1)

好一阵子没看过VB了,但是看来您使用了反序列化XML的错误方法。您使用的方法适用于JSON。

对于XML反序列化,请使用DeserializeXmlNode