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

时间:2015-05-04 19:48:05

标签: json xamarin xamarin.forms

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?

1 个答案:

答案 0 :(得分:1)

您多次反序列化响应。你也有冲突的回报类型; List<RootObject>&amp; RootObject。哪一个是正确的?您可以更改此行:

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

到此(假设返回类型为RootObject而不是List<RootObject>):

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

现在应该可以访问响应对象:

var games = response.Data.games;