0

考虑这个 JSON:

    resourceSets: [
{
estimatedTotal: 5,
resources: [
{
__type: "Location:http://schemas.microsoft.com/search/local/ws/rest/v1",
bbox: [
51.3014406,
-8.3233626,
51.3037489,
-8.3182203
],
name: "Some Address",
point: {
type: "Point",
coordinates: [
51.3033847,
-2.3204335
]
},
address: {
addressLine: "SomeAddress",
adminDistrict: "MI",
adminDistrict2: "South Country",
countryRegion: "England",
formattedAddress: "Some Formattedaddress",
locality: "Derby",
postalCode: "12345"
},

ETC..

紧随其后: http: //blog.clauskonrad.net/2010/11/wp7-how-to-consume-json-data-from.html

我的课是:

[DataContract]
public class ReturnedDetails
{
    [DataMember(Name="formattedAddress")]
    public string formattedAddress { get; set; }

}

和事件代码:

    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        using (var ms = new system.IO.MemoryStream(Encoding.Unicode.GetBytes(e.Result)))
        {
            var ser = new DataContractJsonSerializer(typeof(ReturnedDetails[]));
            ReturnedDetails[] obj = (ReturnedDetails[])ser.ReadObject(ms);
        }
    }

当我运行它时,InvalidCastException会抛出一个ReturnedDetails[] obj = (ReturnedDetails[])ser.ReadObject(ms);

当我调试并将鼠标悬停在ser' KnownDataContractsCould not evaluate expression' 和 'null' 上时。

我只想从 JSON 中的 formattedAddress 中获取值,有人知道怎么做吗?

谢谢你的帮助。

堆栈跟踪是:

在 System.Net.WebClient.DownloadStringOperationCompleted(Object arg) 在 System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e) 在 System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] 参数, CultureInfo System.Reflection.MethodBase.Invoke(Object obj, Object[] 参数) 中的文化、StackCrawlMark 和 stackMark)
在 System.Delegate.DynamicInvokeOne(Object[] args) 在 System.MulticastDelegate.DynamicInvokeImpl(Object[] args) 在 System.Delegate.DynamicInvoke(Object[] args) 在 System.Windows.Threading.DispatcherOperation.Invoke() 在 System .Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority) 在 System.Windows.Threading.Dispatcher.OnInvoke(Object context) 在 System.Windows.Hosting.CallbackCookie.Invoke(Object[] args) 在 System.Windows.Hosting.DelegateWrapper System.Windows.RuntimeHost.ManagedHost.InvokeDelegate 处的.InternalInvoke(Object[] args)
(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)

4

1 回答 1

2

最简单的方法是为整个 JSON 设置类。我使用JSON 2 C#为此编写样板。它将为您提供一些RootObject将 JSON 视为一个整体的类。

WebResponse ws = req.GetResponse();
//Deserialize the JSON
DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(RootObject));
//Cast to root object
RootObject ro = (RootObject)ds.ReadObject(ws.GetResponseStream());

从那里您可以通过您的RootObject遗嘱持有您的ReturnedDetails[].

于 2013-02-09T14:03:24.260 回答