如何使用Refit对数组进行反序列化?

时间:2018-07-18 08:31:32

标签: c# json xamarin refit

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

  

无法反序列化当前JSON对象(例如{“ name”:“ value”})   变成类型'System.Collections.Generic.List`1 [UserItem]',因为   类型需要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更改为dynamic,然后将动态对象解析为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>();

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

1 个答案:

答案 0 :(得分: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);
    }
相关问题