解析webapi发送的数据。 IEnumerable是一个不错的选择吗?

时间:2012-08-08 15:58:28

标签: c# asp.net windows-8 microsoft-metro asp.net-web-api

您好我正在创建WebAPI以及与此API通信的windows8 metro应用。

我将使用简单的例子

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\"]"

我如何解析/转换它?

3 个答案:

答案 0 :(得分:2)

WebAPI默认返回JSON。您可以请求它发送XML,或使用JSON解析器。

答案 1 :(得分:1)

在您的情况下,您可以使用Json.Net轻松反序列化:

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

答案 2 :(得分: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是string []。

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
    }