如何使用DataContractJsonSerializer在WP7中反序列化少量JSON

时间:2012-05-21 23:28:38

标签: json web-services windows-phone-7 deserialization

我试图通过网络请求反序列化JSON结果。

这是我的代码。

    void myButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            WebClient webClient = new WebClient();
            Uri uri = new Uri("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/1/query?text=&geometry=&geometryType=esriGeometryPoint&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&objectIds=&where=POP1999%3E15000000&time=&returnCountOnly=true&returnIdsOnly=false&returnGeometry=false&maxAllowableOffset=&outSR=&outFields=STATE_NAME%2CMALES%2CFEMALES%2CPOP1999&f=json");
            webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
            webClient.OpenReadAsync(uri); 
            //RESULT {"count":4}

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message); 
        }
    }

    void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        DataContractJsonSerializer ser = null;
        try
        {
            //countertext.Text =  DESERIALIZE COUNT HERE
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message); 
        }

    }

    public class Counter
    {
        public int count { get; set; }
    }
}

看起来应该很简单,但我无法理解。

我想在后台代理中使用此代码,而我无法在后台代理中使用ArcGIS运行时for Windows Phone API,因为它是第三方API。

1 个答案:

答案 0 :(得分:2)

它应该没有问题地反序列化:

var ser = new DataContractJsonSerializer(typeof(Counter));
Counter r = (Counter) ser.ReadObject(e.Result);

System.Diagnostics.Debug.WriteLine(r.count);  // 4