最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - JsonSerializer.Deserialize into ObservableCollection - Stack Overflow

programmeradmin0浏览0评论

I receive a player list api in json format and I want to use it in PlayerListViewModel, but I don't know how to deserialize it to the player class.

public partial class PlayerListViewModel : ObservableObject
{
        
    public PlayerListViewModel(){

      PlayerListItems = new ObservableCollection<Player>();

    }
    
     [ObservableProperty]
     ObservableCollection<Player> playerListItems;
}
[RelayCommand]
async Task getPlayersAPI()
{
     var response = await _httpClient.GetAsync(_url);
     var responseString = await response.Content.ReadAsStringAsync();
     playerListItems = JsonSerializer.Deserialize<Player>(responseString);
     //playerListItems = JsonSerializer.Deserialize<List<Player>>(responseString);  
}

Player Class

public class Player
{  
    public int Id {  get; set; }
    public required string fullName { get; set; }
    public required string imageSrc { get; set; }
    public required string countryFlag { get; set; }    
}

Data received example

[
  {
    "Id": 577,
    "fullName": "Bob Smith",
    "imageSrc": "ProfileImage.webp",
    "countryFlag": "us.svg"
  },
  {
    "Id": 744,
    "fullName": "Gee Kingford",
    "imageSrc": "ProfileImage.webp",
    "countryFlag": "ca.svg"
  }
]

How can I populate playerListItems so I can bind that to my XAML form.

The specific error I'm getting is over JsonSerializer.Deserialize

Cannot implicitly convert type '...Player' to 'System.Collections.ObjectModel.ObservableCollection...<Player>'

I receive a player list api in json format and I want to use it in PlayerListViewModel, but I don't know how to deserialize it to the player class.

public partial class PlayerListViewModel : ObservableObject
{
        
    public PlayerListViewModel(){

      PlayerListItems = new ObservableCollection<Player>();

    }
    
     [ObservableProperty]
     ObservableCollection<Player> playerListItems;
}
[RelayCommand]
async Task getPlayersAPI()
{
     var response = await _httpClient.GetAsync(_url);
     var responseString = await response.Content.ReadAsStringAsync();
     playerListItems = JsonSerializer.Deserialize<Player>(responseString);
     //playerListItems = JsonSerializer.Deserialize<List<Player>>(responseString);  
}

Player Class

public class Player
{  
    public int Id {  get; set; }
    public required string fullName { get; set; }
    public required string imageSrc { get; set; }
    public required string countryFlag { get; set; }    
}

Data received example

[
  {
    "Id": 577,
    "fullName": "Bob Smith",
    "imageSrc": "ProfileImage.webp",
    "countryFlag": "us.svg"
  },
  {
    "Id": 744,
    "fullName": "Gee Kingford",
    "imageSrc": "ProfileImage.webp",
    "countryFlag": "ca.svg"
  }
]

How can I populate playerListItems so I can bind that to my XAML form.

The specific error I'm getting is over JsonSerializer.Deserialize

Cannot implicitly convert type '...Player' to 'System.Collections.ObjectModel.ObservableCollection...<Player>'
Share Improve this question edited Feb 1 at 22:04 Jason asked Feb 1 at 21:17 JasonJason 291 silver badge7 bronze badges 3
  • Add the received json data to your question – Mohammad Aghazadeh Commented Feb 1 at 21:30
  • Your code should work correctly check it : https://dotnetfiddle/1e867P whats your problem exactly? – Mohammad Aghazadeh Commented Feb 1 at 21:53
  • @MohammadAghazadeh - I'm using Maui and PlayerListItems is a ObservableCollection of Player – Jason Commented Feb 1 at 22:03
Add a comment  | 

2 Answers 2

Reset to default 0

If your problem is that you don't know how to fill your ObservableCollection

you can try this :

public partial class PlayerListViewModel : ObservableObject
{
    private readonly HttpClient _httpClient;
    private readonly string _url = "https://api.example/players"; // Replace with your API URL

    public PlayerListViewModel()
    {
        _httpClient = new HttpClient();
        PlayerListItems = new ObservableCollection<Player>();    
    }

    [ObservableProperty]
    private ObservableCollection<Player> playerListItems;

    [RelayCommand]
    private async Task GetPlayersAPI()
    {    
        var response = await _httpClient.GetAsync(_url);
        response.EnsureSuccessStatusCode();

        var responseString = await response.Content.ReadAsStringAsync();
        var players = JsonSerializer.Deserialize<List<Player>>(responseString);

        PlayerListItems.Clear();
        foreach (var player in players)
        {
            PlayerListItems.Add(player);
        }      
    }
}

The error you have encountered because JsonSerializer.Deserialize is trying to deserialize the JSON string into a single Player object, but your JSON represents a collection of Player objects. You need to deserialize it into a list or collection of Player objects.

Here's how you can adjust your getPlayersAPI method:

Deserialize the JSON into a List

Populate the ObservableCollection with the deserialized list.

发布评论

评论列表(0)

  1. 暂无评论