2012-08-08 39 views
1

您好,我正在創建WebAPI和與此API進行通信的Windows8 metro應用程序。解析webapi發送的數據。 IEnumerable是不錯的選擇?

我會用簡單的例子

API

public IEnumerable<string> Get() { 
     return new string[] { "value1", "value2" }; 
} 

應用

using (HttpClient client = new HttpClient()) 
     { 
      using (var response = await client.GetAsync(this.apiUri.GetUri("content", "Get"))) 
      { 
       var result = await response.Content.ReadAsStringAsync(); 

      } 
     } 

現在變量的結果是從API響應。但這是一個字符串形式

"[\"value1\",\"value2\"]" 

我該如何解析/轉換?

回答

1

這很容易讓你反序列化回用Json.Net,你的情況:

var json = "[\"value1\",\"value2\"]"; 
var values = JsonConvert.DeserializeObject<string[]>(json); 
+0

這是一個很好的例子。我可以在商業項目中使用它嗎? – Fixus 2012-08-09 14:40:18

+0

是的,當然,它是免費的開源軟件,所以你可以在你的商業項目 – 2012-08-09 14:44:47

+0

中使用它。再次感謝你:) – Fixus 2012-08-09 14:51:38

2

WebAPI默認返回JSON。您可以請求它發送XML或使用JSON解析器。

+0

是的,我知道,它顯示我的XML,當我通過直接調用web瀏覽器URL。但是,我如何通過HttpClient在我的客戶端應用程序中獲取這個JSON或XML?我顯示的webapi方法是默認的。沒有任何改變 – Fixus 2012-08-08 16:08:40

0

我在silverlight中使用我的類(MVCClient.cs)與MVC WebAPI進行通信。在你的情況下,你只是想呼籲:

DoGetMessage<string>(yourUrl, new DataDelegateArray<string>(yourCallbackFunction)); 

那你缺少你的代碼行是:

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); 
T data = (T)serializer.ReadObject(stream); 

其中T是字符串[]。

MVCClient.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Runtime.Serialization.Json; 
using System.Text; 
public class MVCClient 
    { 
     public delegate void DataDelegateArray<T>(T[] objects); 
     public delegate void DataDelegate<U>(U obj); 

    #region Communication Functions 
     public void DoPostMessage<T>(string queryURL, T item, ProcessPOSTResult<T> callback) 
     { 
      DoPostMessage<T, T>(queryURL, item, callback); 
     } 

     public void DoPostMessage<TPost, TReply>(string queryURL, TPost item, ProcessPOSTResult<TReply> callback) 
     { 
#if SILVERLIGHT 
      Uri uri = new Uri(queryURL, UriKind.Absolute); 

      var request = (HttpWebRequest)WebRequest.Create(uri); 
      request.Method = "POST"; 
      request.ContentType = "application/json"; 
      request.BeginGetRequestStream(result => 
       { 
        var req = (HttpWebRequest)result.AsyncState; 
        var stream = req.EndGetRequestStream(result); 

        if (stream != null) 
        { 
         var data = new 
         { 
          name = item 
         }; 


         System.IO.MemoryStream ms = new System.IO.MemoryStream(); 
         DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TPost)); 
         serializer.WriteObject(stream, item); 
         stream.Close(); 
        } 

        req.BeginGetResponse((requestResult) => 
        { 
         var req2 = (HttpWebRequest)requestResult.AsyncState; 
         var response = req2.EndGetResponse(requestResult); 
         var responseStream = response.GetResponseStream(); 
         DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TReply)); 
         TReply responseItem = (TReply)serializer.ReadObject(responseStream); 

         System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => 
         { 
          callback(responseItem); 
         }); 

        }, req); 
       }, request); 

#endif 
     } 

     public void DoGetMessage<T>(string queryURL, DataDelegateArray<T> callback) 
     { 
      DoGetMessage<T[]>(queryURL, result => callback(result)); 
     } 

     public void DoGetMessage<T>(string queryURL, DataDelegate<T> callback) 
     { 
#if SILVERLIGHT 
      Uri uri = new Uri(queryURL, UriKind.Absolute); 

      var request = (HttpWebRequest)WebRequest.Create(uri); 
      request.Method = "GET"; 
      request.Accept = "text/json"; 
      request.BeginGetResponse((result) => 
      { 
       var response = request.EndGetResponse(result); 
       var stream = response.GetResponseStream(); 

       if (stream != null) 
       { 
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); 
        T data = (T)serializer.ReadObject(stream); 
        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => 
        { 
         callback(data); 
        }); 
       } 
       else 
        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => 
        { 
         callback(default(T)); 
        }); 
      }, null); 
#endif 
     } 
     #endregion 
    } 
+0

是的,那是我在找什麼:) var responseStream = response.GetResponseStream(); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TReply)); TReply responseItem =(TReply)serializer.ReadObject(responseStream); 這段代碼是我所需要的核心 – Fixus 2012-08-08 16:28:52