xalom
xalom

Reputation: 41

How to get JSON from api in listview labels in Xamarin C#

I have the following code that retrieves json from an api. This works because when I put a breakpoint on it, it neatly shows the json from the url.

The json looks like this when I put a breakpoint on it

enter image description here

And the code of getting the json from the url looks like this public static List GetAllSpecTypes(string acces_Token, string domain, out bool result) { result = true;

        var specTypes = new List<Specification>();

        if (!string.IsNullOrEmpty(domain))
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    string url = $"{domain}/api/specification/GetSpecificationType";
                    client.BaseAddress = new Uri(url);
                    MediaTypeWithQualityHeaderValue contentType = new MediaTypeWithQualityHeaderValue("application/json");
                    client.DefaultRequestHeaders.Accept.Add(contentType);
                    client.DefaultRequestHeaders.Add("cache-control", "no-cache");
                    client.DefaultRequestHeaders.Add("Authorization", acces_Token);
                    HttpResponseMessage response = client.GetAsync(url).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        string json = response.Content.ReadAsStringAsync().Result;
                        specTypes = JsonSerializer.Deserialize<List<Specification>>(json);
                    }
                    else
                    {
                        result = false;
                    }
                }
            }
            catch (Exception)
            {
                //log!
            }
        }
        return specTypes;
    }

And the json from the breakpoint is this:

"[{\"SpecificationTypeId\":1,\"SpecificationTypeName\":\"Overig\"},{\"SpecificationTypeId\":2,\"SpecificationTypeName\":\"Eten/Drinken\"},{\"SpecificationTypeId\":3,\"SpecificationTypeName\":\"Parkeren\"},{\"SpecificationTypeId\":4,\"SpecificationTypeName\":\"Ander vervoer\"},{\"SpecificationTypeId\":5,\"SpecificationTypeName\":\"Materiaal\"},{\"SpecificationTypeId\":6,\"SpecificationTypeName\":\"Persoonlijke uitgaven\"},{\"SpecificationTypeId\":7,\"SpecificationTypeName\":\"Uitgaven cliënt\"},{\"SpecificationTypeId\":8,\"SpecificationTypeName\":\"Overnachting\"},{\"SpecificationTypeId\":9,\"SpecificationTypeName\":\"Congres / beursbezoek\"},{\"SpecificationTypeId\":10,\"SpecificationTypeName\":\"Brandstof\"},{\"SpecificationTypeId\":11,\"SpecificationTypeName\":\"Auto kosten\"},{\"SpecificationTypeId\":12,\"SpecificationTypeName\":\"Eigen vervoer\"},{\"SpecificationTypeId\":14,\"SpecificationTypeName\":\"Vervoer\"}]"

This method should return the specTypes to a viewmodel. But when I do, it's empty when I put a breakpoint on it.

enter image description here

That code is as follows

        public ViewModel()
        {
            this.Source = new List<SourceItem>();

            var data = Api.GetAllSpecTypes(Settings.AccessToken, Settings.Domain, out var valid);

            foreach (var item in data)
            {
                Source.Add(new SourceItem(item.SpecificationName, item.SpecificationId));
            }
        }

What I want to achieve is that here that json is returned from the api call so that I can bind it to a label in a listview.

The listview xaml looks like this in which I put in the label where I use the following:

                                      <Label
                                            FontSize="18"
                                            LineBreakMode="NoWrap"
                                            Text="{Binding Name}"
                                            TextColor="#474747"
                                            VerticalOptions="FillAndExpand" />

What should be in the label are the specificationnames coming from the json

How can i achieve this?

This is my entire viewmodel according to my question

public class SourceItem : INotifyPropertyChanged { public SourceItem(string name, int id) { this.Name = name; this.Id = id; }

        private string name;

        public string Name
        {
            get { return this.name; }
            set
            {
                this.name = value;
                this.OnPropertyChanged("Name");
            }
        }

        private int id;

        public int Id
        {
            get { return this.id; }
            set
            {
                this.id = value;
                this.OnPropertyChanged("Id");
            }
        }

        private bool isSelected;

        public bool IsSelected
        {
            get { return this.isSelected; }
            set
            {
                this.isSelected = value;
                this.OnPropertyChanged("IsSelected");
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyname)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
        }

    }


    public class ViewModel : INotifyPropertyChanged
    {
        private bool _isSelected = false;

        public bool IsSelected
        {
            get => _isSelected;
            set
            {
                if (_isSelected != value)
                {
                    _isSelected = value;
                    OnPropertyChanged();
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged([CallerMemberName] string name = null)
        {
            if (PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(name));

        }

        public ViewModel()
        {
            this.Source = new List<SourceItem>();

            var data = Api.GetAllSpecTypes(Settings.AccessToken, Settings.Domain, out var valid);

            foreach (var item in data)
            {
                Source.Add(new SourceItem(item.SpecificationName, item.SpecificationId));
            }
        }

        public List<SourceItem> Source { get; set; }
    }

And the Specification Class for the JSON is the following:

  public class Specification
    {
        public int SpecificationId { get; set; }
        public string SpecificationName { get; set; }
        public string SpecificationDescription { get; set; }

    }

How do I get the specification names from the json in the xaml label based on my question?

thanks in advance

Upvotes: 0

Views: 271

Answers (1)

Jason
Jason

Reputation: 89169

your json looks like

"[{\"SpecificationTypeId\":1,\"SpecificationTypeName\"

while your C# classes do not include the "Type" in the name

public class Specification
{
    public int SpecificationId { get; set; }
    public string SpecificationName { get; set; }
    public string SpecificationDescription { get; set; }
}

you either need to rename your C# properties to match the json, or use an attribute to map the name

[JsonProperty("SpecificationTypeId")]
public int SpecificationId { get; set; }

Upvotes: 1

Related Questions