Custom Collection Property Not Serializable

I have a custom collection that has its own properties.

 public interface IPagedList<T>: IList<T>
 {
     int TotalCount { get; }
 }

And I have a class that implemented an interface IPagedList.

 public class PagedList<T> : List<T>, IPagedList<T>
 {
        public PagedList(IQueryable<T> source){
        AddRange(source);
        }

    public int TotalCount { get; private set; }
 }

When I used the class PagedList<T>in my web api application, the property is TotalCountnot serialized.

public class EmpolyeeController : ApiController
{
    public IHttpActionResult Get()
    {
        IPagedList<Employee> response = new PagedList<Employee>(Database.GetEmplyees());

        return Ok(response);
    }

}

The answer is:

[
    {
        "Id": "1230a373-af54-4960-951e-143e75313b25",
        "Name": "Deric"
    }
]

But I want to see the TotalCount property in the json response.

enter image description here

Property in Raw View, as you can see in screencast.

(I think these are Raw View IList serialization problems json.net. How to add Raw View middleware)

+4
source share
1 answer

Not quite perfect, but you can consider it as an object through JsonObjectAttribute:

[JsonObject]
public class PagedList<T> : List<T>, IPagedList<T>
{
    public PagedList(IQueryable<T> source)
    {
        AddRange(source);
    }

    public IEnumerable<T> Data => this.ToList();

    public int TotalCount { get; private set; }
}

public IEnumerable<T> Data => this.ToList();, IEnumerable. this, (). , ToList().

:

{
    "Data": [
        {
            "Foo": "Foo",
            "Bar": "Bar"
        }
    ],
    "TotalCount": 0,
    "Capacity": 4,
    "Count": 1
}

JsonConverter.

, ?

apoach :

MyResponseModel<T>
{
     public int TotalCount { get; set; }
     public IEnumerable<T> Data { get; set; }
}

.

0

Source: https://habr.com/ru/post/1688218/


All Articles