简体   繁体   English

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

[英]How to deserialise Array with Refit?

I have the following error trying to deserialise a Json with Refit in a PCL :尝试在 PCL 中使用 Refit 反序列化 Json 时出现以下错误:

Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[UserItem]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[UserItem]”,因为该类型需要一个 JSON 数组(例如 [1,2,3] ) 以正确反序列化。 To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object.要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为正常的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型)可以从 JSON 对象反序列化的数组或列表)。 JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 Path 'user.id', line 1, position 42.路径“user.id”,第 1 行,位置 42。

I think it comes from the Arrays returned for the interests ?我认为它来自为利益返回的 Arrays ?

{
    "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"]
    }
}

EDIT : Here is how I instantiate Refit :编辑:这是我实例化 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)
));

And how I call the service :以及我如何调用服务:

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

EDIT 2 : I tried to change UserResponse to dynamic and then parse the dynamic object into a UserReponse, but it still strip the interests.编辑 2 :我尝试将 UserResponse 更改为动态,然后将动态对象解析为 UserReponse,但它仍然剥离了兴趣。 And I would loose the benefit of using Refit :我会失去使用 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>();

Am I doing it wrong ?我做错了吗? isn't there a simple way to retrieve Arrays of strings ?没有一种简单的方法来检索字符串数组吗?

I had the same problem, I solved it as follows:我遇到了同样的问题,我解决了以下问题:

The service return, returns string, that is, the raw Json:服务返回,返回字符串,即原始Json:

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

And in the code where I call the service, I treat Json:在我调用服务的代码中,我对待 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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM