簡體   English   中英

如何使用 Refit 反序列化數組?

[英]How to deserialise Array with 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。

我認為它來自為利益返回的 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"]
    }
}

編輯:這是我實例化 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>();

我做錯了嗎? 沒有一種簡單的方法來檢索字符串數組嗎?

我遇到了同樣的問題,我解決了以下問題:

服務返回,返回字符串,即原始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);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM