Home > OS >  Mapping json string to a list of custom objects
Mapping json string to a list of custom objects

Time:10-05

this seems as if it should be a very simple task, but it's bugging me

So I am getting some json as a string from a API call. It looks like this:

{
    "results": [
        {
            "id": 375196074679,
            "url": "https://dong.com",
            "name": "Malin Westling",
            "email": "[email protected]",
            "created_at": "2020-11-10T12:53:23Z",
            "updated_at": "2020-11-10T12:53:24Z",
            "time_zone": "Paris",
            "iana_time_zone": "Europe",
            "phone": null,
            "shared_phone_number": null,
            "photo": null,
            "locale_id": 1000,
            "locale": "da",
            "organization_id": null,
            "role": "end-user",
            "verified": false,
            "external_id": null,
            "tags": [],
            "alias": null,
            "active": true,
            "shared": false,
            "shared_agent": false,
            "last_login_at": null,
            "two_factor_auth_enabled": false,
            "signature": null,
            "details": null,
            "notes": null,
            "role_type": null,
            "custom_role_id": null,
            "moderator": false,
            "ticket_restriction": "requested",
            "only_private_comments": false,
            "restricted_agent": true,
            "suspended": false,
            "default_group_id": null,
            "report_csv": false,
            "user_fields": {},
            "result_type": "user"
        },
        {
            "id": 369740043554,
            "url": "https://google.com",
            "name": "ThatGuy",
            "email": "[email protected]",
            "created_at": "2018-11-28T08:20:23Z",
            "updated_at": "2018-11-28T08:20:23Z",
            "time_zone": "Copenhagen",
            "iana_time_zone": "Europe/Copenhagen",
            "phone": null,
            "shared_phone_number": null,
            "photo": null,
            "locale_id": 1000,
            "locale": "da",
            "organization_id": null,
            "role": "end-user",
            "verified": false,
            "external_id": null,
            "tags": [],
            "alias": null,
            "active": true,
            "shared": false,
            "shared_agent": false,
            "last_login_at": null,
            "two_factor_auth_enabled": false,
            "signature": null,
            "details": null,
            "notes": null,
            "role_type": null,
            "custom_role_id": null,
            "moderator": false,
            "ticket_restriction": "requested",
            "only_private_comments": false,
            "restricted_agent": true,
            "suspended": false,
            "default_group_id": null,
            "report_csv": false,
            "user_fields": {},
            "result_type": "user"
        },
    "facets": null,
    "next_page": null,
    "previous_page": null,
    "count": 2
    }

And I have this simple model, where I need to map some json fields to the model fields:

internal class UserModel
{
    public int Id { get; set; }
    public string email { get; set; }
    public DateTime created_at { get; set; }
    public DateTime updated_at { get; set; }
}

and so I tried what seems to be the most standard way of solving this issue, with newtonsoft .Json:

                // Reading api response as string
                string content = await result.Content.ReadAsStringAsync();
                // trying to deserialize to a list of usermodel
                List<UserModel> jObject = JsonConvert.DeserializeObject<List<UserModel>>(content);

Which results in this:

    Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 
'System.Collections.Generic.List`1[ZendeskCleanUp.Models.UserModel]' 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<T>) 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 'results', line 1, position 11.

So there is some issue with the formatting of the json, where it does not seem to reckonize it as a json array.

I guess this makes sense, as it's actually the "results" object that is wrapping an array (i'm not a json pro).

This seems fairly simple, but I just can't figure out how I can be allowed to grab this array of objects and throw the relevant fields into my objects.

While looking, I also found elaborate answers for similar questions, like this one. I guess this could be a valid solution, but it seems like a lot of code, for what in my mind should be a very trivial task.

Edit The question was closed, since it was judged that it was a duplicate. However, the solution in the linked question simply renders mee with a null object.

I now have the classes:

internal class UserModel
{
    public int Id { get; set; }
    public string email { get; set; }
    public DateTime created_at { get; set; }
    public DateTime updated_at { get; set; }
}


internal class CaptureClass
{
    List<UserModel> users  { get; set; }
}

and use this line to deserialize:

var jObject = JsonConvert.DeserializeObject<CaptureClass>(content);

Which results in a Jobject, which is a CaptureClass with a null Users field.

CodePudding user response:

you have to fix your class at first, id should a long type, int is not big enough.

internal class UserModel
{
    public long Id { get; set; }
    public string email { get; set; }
    public DateTime created_at { get; set; }
    public DateTime updated_at { get; set; }
}

After this, if you need only a list of UserModel, you can just parse your json, and deserialize only a list

List<UserModel> results = JObject.Parse(content)["results"].ToObject<List<UserModel>>(); 
  • Related