0

I have the following error trying to deserialise a Json with Refit in a PCL :

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[UserItem]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'user.id', line 1, position 42.

I think it comes from the Arrays returned for the interests ?

{
    "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 :

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. And I would loose the benefit of using 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 ?

GreuM
  • 155
  • 11
  • can you post your C# code? – Prashant Pimpale Jul 18 '18 at 08:32
  • @PrashantPimpale here is the code, thank you for your help :) – GreuM Jul 19 '18 at 09:27
  • Use `dynamic` to parse the JSON – Prashant Pimpale Jul 19 '18 at 09:39
  • Have a look at: https://stackoverflow.com/a/46184976/7124761 – Prashant Pimpale Jul 19 '18 at 09:41
  • Thank you for your help @PrashantPimpale. I tried to change the return type to dynamic. I now get a dynamic object containing all of the parameters, including the interests. I should now convert that object to a UserResponse. However, the method I tried still strip the interests...And I loose all the benefits of using Refit If I have to go that way... I Edited the questions with thoses steps. What do you think ? – GreuM Jul 19 '18 at 10:39

1 Answers1

1

I had the same problem, I solved it as follows:

The service return, returns string, that is, the raw Json:

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

And in the code where I call the service, I treat 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);
    }
Abner
  • 11
  • 1