简体   繁体   中英

Pagination Newtonsoft.Json

A problem I've been running into recently is dealing with pagination of Json I receive from the server. I can work around some instances but would like a better approach. So the structure I receive here illustrates a problem I can run into:

Modules
{
    ID
    Title
    Description
    Lessons
    {
        edges
        {
            node
            {
                ID
            }
        }
    }
}

So for the lessons array, the server inserts the edges and node elements because of the use of pagination. So what I would expect instead is:

Modules
{
    ID
    Title
    Description
    Lessons
    {
        ID
    }
}

The main problem however with this is that it stops me being able to deserialize the object easily, ie I can't do this:

Modules[] modules = JsonConvert.DeserializeObject<Modules[]>(json, settings);

My Lesson and Module class for reference is just:

public class Lesson
{
    public int ID;
}

[System.Serializable]
public class Module
{
    public string ID;
    public string Title;
    public string Description;
    public Lesson[] Lessons;
}

So just wondered if anyone else had come across a similar issue and what solutions they've done to work around it?

Your serialization should work just fine if you create concrete objects for 'edges' and 'node'.

I assume 'lessons' it an array of 'edge' object. 'edge' object contains the 'node' object, which has the property 'id'

So I worked out a bit of a workaround (sort of following Zero Cool's answer) which is to make generic Edges and Node classes. ie

[System.Serializable]
public class Edges<T>
{
    public Node<T>[] edges;
}

public class Node<T>
{
    public T node;
}

And then declare them where I am using Pagination. It's not lovely but works alright as I usually know what is/isn't paginated.

Would still be interested if there's a cleaner way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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