从我发送的帖子请求中读取我的json响应 [英] reading my json response from a post request i sent

查看:115
本文介绍了从我发送的帖子请求中读取我的json响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个post请求类,可以重复使用该类来向外部api发出POST请求,并返回它们发送给我的对象(JSON):

I made a post request class that I could re-use to make POST requests to an external api and return the objects they send me (JSON):

class PostRequest
    {
        private Action<DataUpdateState> Callback;

        public PostRequest(string urlPath, string data, Action<DataUpdateState> callback)
        {
            Callback = callback;

            // form the URI
            UriBuilder fullUri = new UriBuilder(urlPath);
            fullUri.Query = data;

            // initialize a new WebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri.Uri);
            request.Method = "POST";

            // set up the state object for the async request
            DataUpdateState dataState = new DataUpdateState();
            dataState.AsyncRequest = request;

            // start the asynchronous request
            request.BeginGetResponse(new AsyncCallback(HandleResponse),
                dataState);
        }

        private void HandleResponse(IAsyncResult asyncResult)
        {
            // get the state information
            DataUpdateState dataState = (DataUpdateState)asyncResult.AsyncState;
            HttpWebRequest dataRequest = (HttpWebRequest)dataState.AsyncRequest;

            // end the async request
            dataState.AsyncResponse = (HttpWebResponse)dataRequest.EndGetResponse(asyncResult);
            if (dataState.AsyncResponse.StatusCode.ToString() == "OK")
            {
                Callback(dataState); // THIS IS THE LINE YOU SHOULD LOOK AT :)
            }
        }
    }

    public class DataUpdateState
    {
        public HttpWebRequest AsyncRequest { get; set; }
        public HttpWebResponse AsyncResponse { get; set; }
    }
}

Callback方法获取datastate对象并将其推送到此函数:

the Callback method gets the datastate object and pushes it to this function:

    public void LoadDashboard( DataUpdateState dataResponse )
    {
        Stream response = dataResponse.AsyncResponse.GetResponseStream();
        //Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        //StreamReader readStream = new StreamReader(response, encode);
        //readStream.Close();


        Deployment.Current.Dispatcher.BeginInvoke(() => {
            App.RootFrame.Navigate(new Uri("/Interface.xaml", UriKind.RelativeOrAbsolute));
        });
    }

我现在不确定如何获取已从API发送给我的回复的正文.它返回的是json格式,我需要能够将其映射到一个不错的C#类,并使用它在手机上显示内容.

I'm now unsure of how to get the body of that reply that has been sent to me from the API. It is returning a json format, I need to be able to map it to a nice C# class and use it to display stuff on the phone.

我找不到不使用JSON.NET(没有Windows Phone 8程序集的示例)

I can't find an example that doesn't use JSON.NET (which doesn't have an assembly for windows phone 8)

这是我安装HTTPClient类的错误:

This is error I get installing HTTPClient class:

Attempting to resolve dependency 'Microsoft.Bcl (≥ 1.1.3)'.
Attempting to resolve dependency 'Microsoft.Bcl.Build (≥ 1.0.4)'.
Successfully installed 'Microsoft.Bcl.Build 1.0.10'.
Successfully installed 'Microsoft.Bcl 1.1.3'.
Successfully installed 'Microsoft.Net.Http 2.2.13'.
Successfully added 'Microsoft.Bcl.Build 1.0.10' to UnofficialPodio.
Executing script file ***\packages\Microsoft.Bcl.Build.1.0.10\tools\Install.ps1'.
This reference cannot be removed from the project because it is always referenced by the compiler.
This reference cannot be removed from the project because it is always referenced by the compiler.
This reference cannot be removed from the project because it is always referenced by the compiler.
This reference cannot be removed from the project because it is always referenced by the compiler.
Executing script file ***\packages\Microsoft.Bcl.Build.1.0.10\tools\Uninstall.ps1'.
Successfully uninstalled 'Microsoft.Bcl 1.1.3'.
Successfully uninstalled 'Microsoft.Bcl.Build 1.0.10'.
Install failed. Rolling back...
Failed to add reference to 'System.IO'.


"{
    \"access_token\": \"123803120312912j\",
    \"token_type\": \"bearer\",
    \"ref\": {
        \"type\": \"user\",
        \"id\": 123123
    },
    \"expires_in\": 28800,
    \"refresh_token\": \"234234f23f423q432f\"
}"

...

public class Auth
{

    [DataMember(Name = "access_token")]  
    public string AccessToken { get; set; }

    [DataMember(Name = "token_type")]  
    public string TokenType { get; set; }

    [DataMember(Name = "expires_in")]  
    public string ExpiresIn { get; set; }

    [DataMember(Name = "refresh_token")]  
    public string RefreshToken { get; set; }

    //[DataMember(Name = "ref")]  
    //public string Ref { get; set; }

}

推荐答案

要获取响应数据,您需要在HttpWebResponse对象上调用GetResponseStream(),然后从流中读取.像这样:

To get the response data you need to call GetResponseStream() on the HttpWebResponse object and then read from the stream. Something like this:

using (Stream s = response.GetResponseStream())
{
    using (TextReader textReader = new StreamReader(s, true))
    {
        jsonString = textReader.ReadToEnd();
    }
}

要从json字符串中获取数据,您需要创建一个数据协定类来完全像这样描述json数据:

To get the data from the json string, you need to create a data contract class to describe the json data exactly like this:

    [DataContract]
    public class ApiData
    {
        [DataMember(Name = "name")]  <--this name must be the exact name of the json key
        public string Name { get; set; }

        [DataMember(Name = "description")]
        public string Description { get; set; }
    }

接下来,您可以从字符串中反序列化json对象:

Next you can deserialize the json object from the string:

        using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ApiData));
            ApiData obj = (ApiData)serializer.ReadObject(stream);
            return obj;
        }

WebRequest可以正常工作,但是我建议为HttpClient类安装​​NuGet软件包.它使生活变得简单得多.例如,您可以只用几行就可以生成上述请求代码:

WebRequest will work fine, but I would recommend installing the NuGet package for the HttpClient class. It makes life much simpler. for instance, you could make the above request code in just a few lines:

        HttpClient httpClient = new HttpClient();
        HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), escapedUrl);
        HttpResponseMessage response = await httpClient.SendAsync(msg);

在回答以下问题时,这是我使用的通用json转换器代码:

In answer to you question below, here is the generic json converter code that I use:

public static class JsonHelper
{
    public static T Deserialize<T>(string json)
    {
        using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T obj = (T)serializer.ReadObject(stream);
            return obj;
        }
    }

    public static string Serialize(object objectToSerialize)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());
            serializer.WriteObject(ms, objectToSerialize);
            ms.Position = 0;
            using (StreamReader sr = new StreamReader(ms))
            {
                return sr.ReadToEnd();
            }
        }
    }
}

这篇关于从我发送的帖子请求中读取我的json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆