Let's say I have these entitites with these relations: This is just a fictious example, and not my current entities.
Courses have many Users, Users have many Courses
Courses has many NewsPosts, NewsPosts has many Courses
Users has many NewsPosts, NewsPosts has Many Users
I'm using Entity Framework code first with .NET Web API, which sends back entities in the form of JSON. When I try to Get a Course, it sends back a JSON result with the relations of the entites, which is fine, but I would wish to set a limit of how many levels it serializes so it does not serialize all the relations beyond the first or second level.
GET Course/ would be serialized to:
{
"Users":[{
"id":1,
"newsPosts": [{
"id":1,
"message":"foo"
}]
}],
"newsPosts":[{
"id":2,
"message":"bar"
}]
}
What i would want is to serialize only 1 or maybe 2 levels, So that the result would be:
{
"Users":[{
"id":1,
"newsPosts": []
}],
"newsPosts":[{
"id":2,
"message":"bar"
}]
}
I have added a:
json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
This is to remove the referencelooping.
So in short: Is there any way of setting a maximum amount of nodes to serialize?
Property Value The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data.
Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a JsonReaderException. A null value means there is no maximum. The default value is null.
Text. Json is much faster than the Newtonsoft. Json.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
The way I see it you have 2 options:
One of the best practices when it comes to APIs is to only send back the data which is needed because this affects the size of the data sent back.
Entity Framework works in a certain way by providing way too much and you want to limit that. A common way of solving this problem is to not have the API return Entity Framework entities. There are a number of reasons for that which can be researched separately.
So, one approach would be to start using DTOs to return data. This has a number of advantages:
Disadvantages:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With