Thomas Oe
Thomas Oe

Reputation: 11

Cannot deserialize - JSON.NET - Xamarin

I'm struggling with below message. Other JSON objects in the same app work correctly.

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array
(e.g. [1,2,3]) into type 'Monkeys.Models.Rootobject' because the type requires a JSON
object (e.g. {"name":"value"}) to deserialize correctly.

I have the following output from the API via web browser:

[{"Id":"1","Name":"Monkey 1","Location":null,"Details":null,"SKU":null,"Size":null,
"Color":null,"Image":null,"Brand":null,"NameSort":"M"},{"Id":"2","Name":"Monkey 2",
"Location":null, "Details":null,"SKU":null,"Size":null,"Color":null,"Image":null,
"Brand":null,"NameSort":"M"}]

The Model in my App:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Monkeys.Models
{
  public class Monkey
  {
    public string Id { get; set; }
    public string Name {get;set;}
    public string Location { get; set; }
    public string Details { get; set; }
    //URL for our monkey image!
    public string SKU { get; set; }
    public string Size { get; set; }
    public string Color { get; set; }
    public string Image { get; set; }

    public string Brand { get; set; }

    public string NameSort
    {
        get
        {
            if (string.IsNullOrWhiteSpace(Name) || Name.Length == 0)
                return "?";

            return Name[0].ToString().ToUpper();
        }
    }
}

 public class Rootobject
 {
    public Monkey[] monkeys { get; set; }
 }
}



The App:

using System;
using System.Net;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Monkeys.Models;
using System.Collections.Generic;

namespace Monkeys.Apis 
{


public class GetMonkeys
{
    public GetMonkeys()
    {
    }


    public async Task<Monkey[]> GetMonkeysAsync()
    {

        var client = new System.Net.Http.HttpClient();

        client.BaseAddress = 
new Uri("https://microsoft-                                             apiappce13ac35390d40a684dd6ab72a9eef8f.azurewebsites.net:443/");
        var response = await client.GetAsync("api/Monkey");

        var earthquakesJson = response.Content.ReadAsStringAsync().Result;


        var rootobject = JsonConvert.DeserializeObject<Rootobject>        (earthquakesJson);


        return rootobject.monkeys;

    }


}

}

Upvotes: 1

Views: 2877

Answers (1)

Jason
Jason

Reputation: 89082

Your json data is an array of Monkey. Try this

// monkeys will be a List<Monkey>
var monkeys = JsonConvert.DeserializeObject<List<Monkey>>(earthquakesJson);

Upvotes: 1

Related Questions