How to get data from JSON in wp7

本文关键字:JSON in wp7 from data to get How | 更新日期: 2023-09-27 17:58:23

考虑这个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"
},

等等。。

紧随其后: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上时,KnownDataContracts为"无法计算表达式"answers"null"。

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

谢谢你的帮助。

堆栈跟踪为:

在PhoneApp1.MainPage.wc_DownloadStringCompleted(对象发送方,在下载StringCompletedEventArgs e)System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgse) 位于System.Net.WebClient.DownloadStringOperationCompleted(对象arg)System.Reflection.RuntimeMethodInfo.InteralInvoke(RuntimeMethodInfortmi,Object obj,BindingFlags invokeAttr,Binder Binder,Object参数,CultureInfo区域性,布尔值isBinderDefault,程序集caller,Boolean verifyAccess,StackCrawlMark&stackMark)System.Reflection.RuntimeMethodInfo.InteralInvoke(对象obj,BindingFlags invokeAttr,Binder Binder,Object[]参数,CultureInfo文化,StackCrawlMark&stackMark)System.Reflection.MethodBase.Invoke(Object obj,Object[]参数)
位于的System.Delegate.DynamicInvokeOne(Object[]args)位于的System.MulticastDelegate.DynamicInvokeImpl(Object[]args)位于的System.Delegate.DynamicInvoke(Object[]args)位于的System.Windows.Threading.DispatcherOperation.IInvoke()System.Windows.Threading.Dispatcher.Dispatcher(DispatcherPriority优先级)(对象上下文)在System.Windows.Hosting.CallbackCookie.Invoke(Object[]args)System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[]args)
位于System.Windows.RuntimeHost.ManagedHost.IInvokeDelegate(IntPtrpHandle,Int32 nParamCount,ScriptParam[]pParams,ScriptParam&pResult)

How to get data from JSON in wp7

最简单的方法是为整个JSON创建类。我使用JSON2C#来编写这方面的样板文件。它将为您提供一些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[]