简体   繁体   中英

consume web service in xamarin.forms json

I want to display the value of the source to the List view on the button Name and Image Logo as I as result I have bind the Image source and Name. However there seems to be no results displayed.

public async Task<string> GetRequest (string url){
    Uri geturi = new Uri("http://172.20.129.193/nypstudentlifeservice/"); 
    HttpClient client = new HttpClient();
    HttpResponseMessage responseGet = await client.GetAsync(geturi);
    return responseGet.Content.ReadAsStringAsync().Result;
}

public async Task<IEnumerable<CsClubList>> getClubList()
{
    string result = await GetRequest("api/club/list?categoryid=2");

    CsClubList[] clublist = null;

    var clubtoken = JObject.Parse(result)[0];

    clublist = clubtoken.Select(clublists => new CsClubList()
    {
        Id = (int)clublists["Id"],
        Name = (string)clublists["Name"],
        Logo = (string)clublists["Logo"],
        CategoryId = (int)clublists["CategoryId"]
    }).ToArray();

    return clublist;
}

This are the codes that I did to try to consume the Json web service.

This is the class file of the CsClubList

public class CsClubList
{
    public int Id{ get; set;}
    public int CategoryId { get; set; }
    public string Name {get; set;}
    public string Logo {get; set;}
}

For the xaml.cs file

public partial class ListClubs : ContentPage
{
    private IEnumerable<CsClubList> _ClubList;

    public ListClubs ()
    {
         InitializeComponent();
         setClubs(Clublistview); //The statement is not awaited and execution of current method continues before the call is complete. Consider using 'await' operator or calling 'Wait' method
    }


    public IEnumerable<CsClubList> ClubList 
    {
        get { return _ClubList; }
        set { _ClubList = value; }
    }

    private async void setClubs(ListView listview)
    {
        ClubApiClient service = new ClubApiClient();
        var clublist = await service.getClubList();
        listview.ItemsSource = clublist.ToList();
    }
}

This is the xaml page:

<ListView  x:Name="Clublistview">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout BackgroundColor="White"
                    Orientation="Vertical">
                        <StackLayout Orientation="Horizontal">
                            <Image Source="{Binding Logo}" IsVisible="true" WidthRequest="42" HeightRequest="42"/>
                             <Button Text="{Binding Name}" x:Name="BtnClub" AbsoluteLayout.LayoutBounds="100, 25, 100, 25" Clicked="OnListClubsClicked" TextColor="Black" VerticalOptions="FillAndExpand"/>
                        </StackLayout>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

this is the link for the Json web service:

http://172.20.129.193/nypstudentlifeservice/api/club/list?categoryid=2

[{"Id":21,"CategoryId":2,"Name":"Chinese Cultural Group","Logo":"http://www.nyp.edu.sg/web/campus_life/cca/arts_&_culture/image/CCG2.png"},{"Id":22,"CategoryId":2,"Name":"Chinese Orchestra","Logo":"http://www.nyp.edu.sg/web/campus_life/cca/arts_&_culture/image/CO-ICON.png"},{"Id":23,"CategoryId":2,"Name":"Dance Company","Logo":"http://www.nyp.edu.sg/web/campus_life/cca/arts_&_culture/image/DC2.png"},{"Id":24,"CategoryId":2,"Name":"Danz Inc.","Logo":"http://www.nyp.edu.sg/web/campus_life/cca/arts_&_culture/image/DI-ICON.png"},{"Id":25,"CategoryId":2,"Name":"Der Treff German Club","Logo":"http://www.nyp.edu.sg/web/campus_life/cca/arts_&_culture/image/DTG-ICON.png"},{"Id":26,"CategoryId":2,"Name":"Foreign Bodies Dance Group","Logo":"http://www.nyp.edu.sg/web/campus_life/cca/arts_&_culture/image/FB-ICON.png"}]

You haven't really stated what the problem is or what is your question, but here are some observations based on the code you provided.

You are mixing async and synchronous calls in your code. Don't use .Result or .Wait in an async method.

Remove .Result from the line where you are trying to read the response as string and await the result just as you did with the HTTP request.

Also noticed that you were not constructing the Uri for your request properly. You created a Uri with the base address but did not include the url parameter provided.

public async Task<string> GetRequest(string url) {
    Uri getUri = new Uri("http://172.20.129.193/nypstudentlifeservice/" + url);
    HttpClient client = new HttpClient();
    HttpResponseMessage responseGet = await client.GetAsync(getUri);
    responseGet.EnsureSuccessStatusCode(); // Throw if not a success code.
    string content = await responseGet.Content.ReadAsStringAsync();
    return content;
}

public async Task<IEnumerable<CsClubList>> getClubList() {
    string json = await GetRequest("api/club/list?categoryid=2");

    List<CsClubList> clublist = JsonConvert.DeserializeObject<List<CsClubList>>(json);

    return clublist;
}

You should also where possible using async on void methods unless they are event handlers.

So if possible you need to change this

//NO NO NO NO NO
private async void setClubs(ListView listview)
{
    ClubApiClient service = new ClubApiClient();
    var clublist = await service.getClubList();
    listview.ItemsSource = clublist.ToList();
}

To this

private async Task setClubs(ListView listview)
{
    ClubApiClient service = new ClubApiClient();
    var clublist = await service.getClubList();
    listview.ItemsSource = clublist.ToList();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM