【问题标题】:Cannot deserialize the current JSON array (e.g. [1,2,3]) in Xamarin studio无法在 Xamarin Studio 中反序列化当前 JSON 数组(例如 [1,2,3])
【发布时间】:2015-05-04 19:48:05
【问题描述】:

当我在 Xamarin 表单上运行我的 iOS 应用程序时出现此错误。 我正在使用 WEB API 并尝试在我的移动应用程序中显示该结果。

我的webservice方法是:

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;
    }
}

我的模型类是:

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;}
}

有什么帮助可以解决这个错误吗?

【问题讨论】:

    标签: json xamarin xamarin.forms


    【解决方案1】:

    您正在多次反序列化响应。您还有冲突的返回类型; List&lt;RootObject&gt; & RootObject。哪一个是正确的?您可以更改此行:

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

    对此(假设返回类型是RootObject 而不是List&lt;RootObject&gt;):

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

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

    var games = response.Data.games;
    

    【讨论】:

      猜你喜欢
      • 2014-03-20
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 2019-03-20
      • 2018-12-30
      相关资源
      最近更新 更多