When I go to serialize the RageResult object with newtonsoft the serialized string contains only the data from the 'Items' property

Here is the code:

List<string> listString = new List<string>
{
    "Test1", 
    "Test2"
};

var pageResultTest = new PageResult<string>(listString, null, 2);
string serialized = JsonConvert.SerializeObject(pageResultTest, Formatting.Indented);

The pageResult object is serialized in this way:

[
  "Test1",
  "Test2"
]

The serialization I would expect and want to achieve is this:

{
  "Items": [
      "Test1",
      "Test2"
  ],
  "NextPageLink": null,
  "Count": 2
}
1

There are 1 best solutions below

2
jakub podhaisky On

PageResult is specifically designed for Razor Page applications to produce an IActionResult that renders a page. It's not meant to be used as a data container for serialization purposes. That's why when you try to serialize it directly, you're not getting the expected structure in JSON.

pageResult documentation

for the functionality you are after you will need to implement your own custom object that represents the structure you are after:

public class CustomPageResult<T>
{
    public List<T> Items { get; set; }
    public string NextPageLink { get; set; }
    public int Count { get; set; }

    public CustomPageResult(List<T> items, string nextPageLink, int count)
    {
        Items = items;
        NextPageLink = nextPageLink;
        Count = count;
    }
}

Sample get api

[HttpGet]
public ActionResult<CustomPageResult<string>> GetItems()
{
    List<string> items = new List<string> { "Item1", "Item2" }; // Your logic here
    string nextPageLink = null; // Your logic here
    int count = items.Count;

    var response = new CustomPageResult<string>(items, nextPageLink, count);
    return Ok(response);
}

Than you can seriliaze:

List<string> listString = new List<string>
{
    "Test1", 
    "Test2"
};

var customPageResult = new CustomPageResult<string>(listString, null, 2);
string serialized = JsonConvert.SerializeObject(customPageResult, Formatting.Indented);

you will get the desired output:

{
  "Items": [
      "Test1",
      "Test2"
  ],
  "NextPageLink": null,
  "Count": 2
}