Aabi Regmi
Aabi Regmi

Reputation: 33

Cannot deserialize the current JSON array (e.g. [1,2,3]) in Xamarin studio

I get this error when i run my iOS application on Xamarin forms. I am consuming from a WEB API and trying to show that result in my mobile application.

My webservice method is:

public async Task<Game[]> GetGamesAsync() {

    var client = new RestClient("http://gams/GameStore2/");
    var request = new RestRequest ("api/Games", Method.GET);
    request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

    var apiKey = Application.Current.Properties ["ApiKey"];
    var userId = Application.Current.Properties ["UserId"];

    try {
        request.AddHeader ("key",apiKey.ToString ());
        request.AddHeader ("id",userId.ToString ());
    }
    catch{}

    IRestResponse response = client.Execute <List<RootObject>>(request);
    statusCodeCheck (response);
    Console.WriteLine ("here" + response.Content);
    var gameJson = response.Content;

    if (response.StatusCode == HttpStatusCode.OK) {
        var rootObject = JsonConvert.DeserializeObject<RootObject>(gameJson);
        return rootObject.games;
    }
    else {
        return null;
    }
}

and my model class is :

public class Game
{
    public int GameId {get;set;}
    public string GameName { get; set; }
    public DateTime ReleaseDate { get; set;}
    public decimal Price { get; set;}
    public int InventoryStock { get; set;}
    public bool check { get; set;}
    public List<Genre> Genres { get; set;}
    public List<Tag> Tags { get; set;}
}

public class RootObject{
    public Game[] games { get; set;}
}

Any help to fix this error?

Upvotes: 1

Views: 573

Answers (1)

SKall
SKall

Reputation: 5234

You are de-serializing the response multiple times. You also have conflicting return types; List<RootObject> & RootObject. Which one is correct? You can change this line:

IRestResponse response = client.Execute <List<RootObject>>(request);

to this (assuming the return type is RootObject and not List<RootObject>):

var response = client.Execute <RootObject>(request);

Now the response object should be accessible:

var games = response.Data.games;

Upvotes: 1

Related Questions