【问题标题】:How to deserialise Array with Refit?如何使用 Refit 反序列化数组?
【发布时间】:2018-07-18 08:31:32
【问题描述】:

尝试在 PCL 中使用 Refit 反序列化 Json 时出现以下错误:

无法反序列化当前 JSON 对象(例如 {"name":"value"}) 进入类型“System.Collections.Generic.List`1[UserItem]”,因为 type 需要一个 JSON 数组(例如 [1,2,3])才能正确反序列化。到 修复此错误或者将 JSON 更改为 JSON 数组(例如 [1,2,3]) 或更改反序列化类型,使其成为普通的 .NET 类型(例如 不是像整数这样的原始类型,不是像数组这样的集合类型 或列表)可以从 JSON 对象反序列化。 JsonObjectAttribute 也可以添加到类型中以强制它 从 JSON 对象反序列化。路径“user.id”,第 1 行,位置 42。

我认为它来自为兴趣返回的数组?

{
    "error": {
        "code": 0,
        "msg": ""
    },
    "user": {
        "id": "5",
        "first_name": "test",
        "last_name": "test",
        "email": "a@gmail.com",
        "auth_token": "****",
        "date_of_birth": "0001-05-06 00:00:00",
        "group_id": "1",
        "group_name": null,
        "postal_code": "56456",
        "city": "Annecy",
        "country": "France",
        "facebook_id": null,
        "facebook_img": null,
        "status": null,
        "is_activated": null,
        "gcm_id": "GHJK",
        "device_id": null,
        "platform": "android",
        "interest": ["1", "2"],
        "profile_pic": "profile.jpg",
        "cover_img": "cover.jpg",
        "address": null,
        "invoicing_address": "address",
        "invoicing_city": "city",
        "invoicing_country": "",
        "invoicing_postal_code": "78654",
        "gender": null,
        "company_no": "1234",
        "company_name": "",
        "about_company": "",
        "company_logo": "",
        "company_legal_name": "lumao",
        "company_contact_no": "",
        "company_address": "",
        "company_city": "",
        "company_country": "",
        "company_postal_code": "",
        "vat_no": "",
        "telephone": null,
        "membership_status": null,
        "contact_status": 2,
        "company_interests": [],
        "needs": ["not_implemented"]
    }
}

编辑: 这是我实例化 Refit 的方式:

Func<HttpMessageHandler, IFlairPlayApi> createClient = messageHandler =>
            {
                var client = new HttpClient(messageHandler)
                {
                    BaseAddress = new Uri(ApiBaseAddress)
                };

                return RestService.For<IFlairPlayApi>(client);
            };

NativeMessageHandler msgHandler = new NativeMessageHandler();
        msgHandler.DisableCaching = true;
        _speculative = new Lazy<IFlairPlayApi>(() => createClient(

            new RateLimitedHttpMessageHandler(msgHandler, Priority.Speculative)
));

以及我如何调用服务:

[Get("/getuser.json")]
Task<UserResponse> GetUser(int userid, int contact_id, string langval);

编辑 2: 我尝试将 UserResponse 更改为动态,然后将动态对象解析为 UserReponse,但它仍然剥夺了兴趣。而且我会失去使用 Refit 的好处:

    [Get("/getuser.json")]
    Task<dynamic> GetUser(int userid, int contact_id, string langval);

dynamic userObject = await FPApi.Speculative.GetUser(user.id, contact_id, FPEngine.Instance.Lang);
                JObject jUser = userObject as JObject;
                UserResponse response = jUser.ToObject<UserResponse>();

我做错了吗?难道没有一种简单的方法来检索字符串数组吗?

【问题讨论】:

  • 你能发布你的 C# 代码吗?
  • @PrashantPimpale 这里是代码,谢谢你的帮助:)
  • 使用dynamic解析JSON
  • 感谢您的帮助@PrashantPimpale。我试图将返回类型更改为动态。我现在得到一个包含所有参数的动态对象,包括兴趣。我现在应该将该对象转换为 UserResponse。但是,我尝试的方法仍然剥夺了兴趣......而且我失去了使用 Refit 的所有好处如果我必须这样做......我用这些步骤编辑了问题。你怎么看?

标签: c# json xamarin refit


【解决方案1】:

我遇到了同样的问题,我解决了如下:

服务返回,返回字符串,即原始Json:

public interface IApiHgFinance
{
    [Get("/taxes?key=minhachave")]
    Task<string> GetTaxes();
}

在我调用服务的代码中,我对待 Json:

    try
    {
        IApiHgFinance ApiHgFinance = Refit.RestService.For<IApiHgFinance>("https://api.hgbrasil.com/finance");
        var result = await ApiHgFinance.GetTaxes();

        var jo = Newtonsoft.Json.Linq.JObject.Parse(result);

        var taxes = jo["results"].ToObject<itemTaxes[]>();
        foreach (var item in taxes)
        {
            MessageBox.Show($"Taxa CDI   : {item.Cdi} \nTaxa Selic : {item.Selic} \nData Atualização: {item.Date}",
                "Atualização de informações", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Erro: {ex.Message}", "Erro ao tentar recuperar as taxas do dia.", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

【讨论】:

    猜你喜欢
    • 2018-02-20
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 2012-06-30
    • 1970-01-01
    • 2016-05-30
    相关资源
    最近更新 更多