How to call a REST web service for Windows 8.1 phone app development

谁说我不能喝 提交于 2019-12-12 18:42:56

问题


I am new to Windows phone app development. I have installed free version of Visual Studio Express 2013 for windows.

I am trying to build a windows phone app for windows phone 8.1. My problem is on button click I want to call a REST back end web service which will return a response JSON Object.

I have looked over the forum but could not find anything which I could Successfully implement.

Can someone please point me to the right direction?

Thanks.


回答1:


Before you start you need to add the following Nuget packages to your project:

  • Json.NET (https://www.nuget.org/packages/Newtonsoft.Json/)
  • Microsoft HTTP Client Libraries (https://www.nuget.org/packages/Microsoft.Net.Http/2.2.28)

If your json looks like this:

[
  {
    "id": "1",
    "title": "Hello"
  }
]

You need to edit the class of your object to "set a link" between the json properties and your object properties:

public class YourObject
    {
        [JsonProperty("id")]
        public String Id{ get; set; }

        [JsonProperty("title")]
        public String Title { get; set; }
    }

Explanation about the method below: U make a new HttpClient() object that u use to make a "GET" to a given url. If the HttpResponse is success (that means data is available), you can do something with the data. In your case its deserialize the json data to an object.

public async Task<YourObject> GetObject()
        {
            YourObject o = new YourObject();

            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.GetAsync(url))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        string content = await response.Content.ReadAsStringAsync();
                        o= await JsonConvert.DeserializeObjectAsync<YourObject>(content);
                    }
                }
            }
            return o;
        }

I hope my explanation is clear enough and that this helps u further.




回答2:


There are plenty of good articles online which have almost the same title as the title of your question. Still, here's a few steps

  1. To make REST calls, you'll want to use a HttpClient class
  2. The response data can be easily pulled out as a JSON string, which you will have to deserialize to your C# object. The best and most popular library to use to work with JSON is JSON.NET.

One of the top search results: Consuming REST Services in your Windows Store and Phone Applications



来源:https://stackoverflow.com/questions/25682877/how-to-call-a-rest-web-service-for-windows-8-1-phone-app-development

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!