pax
pax

Reputation: 1903

Xamarin.Forms WebAPI JsonConverter.DeserializeObject unhandled exception

I'm trying to replicate the functionality in one of MoshHamedani's course on Xamarin Forms. Here's my code (with a valid, working _url, that returns a json object with escape characters):

public partial class PartnersListPage : ContentPage
  {
    private const string _url = "xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyz";
    private HttpClient _httpClient = new HttpClient();
    private ObservableCollection<Partner> _partners;

    public PartnersListPage()
    {
      InitializeComponent();
    }

    protected override async void OnAppearing()
    {
      var jsonObject = await _httpClient.GetStringAsync(_url);
      var dotNetObject = JsonConvert.DeserializeObject<List<Partner>>(jsonObject);

      _partners = new ObservableCollection<Partner>(dotNetObject);

      partnersListView.ItemsSource = _partners;

      base.OnAppearing();
    }

Partner.cs looks like this:

public class Partner
  {
    //public int Id { get; set; }
    //public string Name { get; set; }
    public string ImageUrl { get; set; }
    public string WebUrl { get; set; }
  }

Postman returns the following:

{
    "partners": [
        {
            "imageUrl": "http://www.abcdefgh.xy//media/1007/3.jpg",
            "webUrl": "http://www.abcdefgh.xy/"
        },
        {
            "imageUrl": "http://www.ijklmnop.xy//media/1009/5.jpg",
            "webUrl": "https://www.ijklmnop.xy/xy"
        },
        {
            "imageUrl": "http://www.qrstuvxy.xy//media/2623/slsp.svg",
            "webUrl": "https://www.qrstuvxy.xy/"
        }
    ]
}

When I hit the JsonConvert.DeserializeObject line, I get the following: An unhandled exception occured. Why is it not working?

Upvotes: 1

Views: 283

Answers (2)

Milen
Milen

Reputation: 8867

You are deserializing with incorrect type (List<Partner>) I'm using Json to c# converter in order to determine the class I need - just paste in your json text/data and in will generate the classes for you. For the example for your json text/data you need:

public class Partner
{
    public string imageUrl { get; set; }
    public string webUrl { get; set; }
}

public class RootObject
{
    public List<Partner> partners { get; set; }
} 

........

var result = JsonConvert.DeserializeObject<RootObject>(jsonObject);

Upvotes: 2

levent
levent

Reputation: 3634

controller returning single object but you are trying to array deserialize

public class Partner
  {
    //public int Id { get; set; }
    //public string Name { get; set; }
    public string ImageUrl { get; set; }
    public string WebUrl { get; set; }
  }

public class ApiResult
{
    List<Partner> Partners {get;set;}
}

and..

var dotNetObject = JsonConvert.DeserializeObject<ApiResult>(jsonObject);

Upvotes: 1

Related Questions