当我尝试JsonConvert.DeserializeObject <T>时,我的xamarin应用程序冻结

时间:2019-12-17 14:15:46

标签: c# json xamarin xamarin.forms json.net

当我从HttpClient()获得json响应并尝试进行Deselize时,我的Xamarin应用程序冻结(UI可用,但是ExecuteGetRequest类第15行中的代码不起作用)。是什么原因呢? 没有错误。

我称之为获取动漫用户列表的方法

        ShikimoriMain shikimoriMain = new ShikimoriMain();
        var UserInformation = await shikimoriMain.GetUserInformation(Convert.ToInt64(UserID));
        var UserAnimeList = await shikimoriMain.GetUserAnimeList(Convert.ToInt64(UserID), 1, 5);
        string animeName = UserAnimeList.Anime[0].Anime.Name;

ShikimoriMain.GetUserAnimeList

    public async Task<ShikimoriUserAnimeList> GetUserAnimeList(long id, int page, int limit)
    {
        string[] args = new string[] { ShikimoriCategories.UserID + "/" + id + ShikimoriCategories.UserAnimeList + $"?limit={limit}&page={page}" };
        return await ExecuteGetRequest<ShikimoriUserAnimeList>(args);
    }

ExecuteGetRequest

    public async Task<T> ExecuteGetRequest<T>(string[] args) where T : class
    {
        T returnedObject;

        using (var client = new HttpClient())
        {
            // client.BaseAddress = new Uri($"{httpApiv1}/{args}");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, httpApiv1 + String.Join("/", args));
            request.Headers.TryAddWithoutValidation("User-Agent", "Search Anime");
            HttpResponseMessage responseMessage = await client.SendAsync(request);
            string json = await responseMessage.Content.ReadAsStringAsync(); // successfully get json

            returnedObject = JsonConvert.DeserializeObject<T>(json); // after that the code is not executed

            return returnedObject;
        }
    }

ShikimoriUserAnimeList

public class ShikimoriUserAnimeList
{
    [JsonProperty()]
    public List<GetAnime> Anime { get; set; }
}

public class GetAnime
{
    [JsonProperty("id")]
    public int ID { get; set; }
    [JsonProperty("status")]
    public string Status { get; set; }
    [JsonProperty("anime")]
    public Anime Anime { get; set; }
}

public class Anime
{
    [JsonProperty("id")]
    public int ID { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("russian")]
    public string NameRU { get; set; }
    [JsonProperty("image")]
    public AnimeImage AnimeImage { get; set; }
    [JsonProperty("kind")]
    public string King { get; set; }
    [JsonProperty("score")]
    public string Score { get; set; }
    [JsonProperty("status")]
    public string Status { get; set; }
    [JsonProperty("episodes")]
    public int Episodes { get; set; }
}

public class AnimeImage
{
    [JsonProperty("original")]
    public string Original { get; set; }
    [JsonProperty("preview")]
    public string Preview { get; set; }
    [JsonProperty("x96")]
    public string ImageX96 { get; set; }
    [JsonProperty("x48")]
    public string ImageX48 { get; set; }
}

2 个答案:

答案 0 :(得分:1)

为了完整起见:

引发了一个错误,但在设备日志中不可见。将JsonConvert.DeserializeObject<T>(json)包裹在try catch block中有助于发现被抛出的Exception

try 
{
    returnedObject = JsonConvert.DeserializeObject<T>(json); // after that the code is not executed

    return returnedObject;
}
catch (Exception ex) 
{
 ... (debug and fix the error that occurred)
}

答案 1 :(得分:0)

我遇到了同样的问题,我意识到使用 HttpClient 异步会在 winforms 中导致死锁 xamarin (但是 Asp 配合使用效果很好),我更改了这些行

  HttpResponseMessage responseMessage = await client.SendAsync(request);
  string json = await responseMessage.Content.ReadAsStringAsync(); // successfully get json

喜欢这些(使它们同步工作):

  HttpResponseMessage responseMessage = client.SendAsync(request).Result;
  string json = responseMessage.Content.ReadAsStringAsync().Result; // successfully get json

并将您的方法更改为默认的同步

看看Here