Set maximum JSON serialization depth in .NET Web API

Let's say I have these powers with this relationship: This is just a fictitious example, not my current entities.

  • Course
  • User
  • Newsposts

There are many users in courses, Users have many courses

Courses have a lot of news; NewsPosts has a lot of courses.

Users have a lot of news, NewsPosts have a lot of users

I first use Entity Framework code with the .NET Web API, which dispatches objects in JSON form. When I try to get a course, it sends a JSON result with entites relations, which is good, but I would like to set a limit on the number of levels that it serializes, so it does not serialize all relations outside of the first or second level.

GET Course / will be serialized for:

{ "Users":[{ "id":1, "newsPosts": [{ "id":1, "message":"foo" }] }], "newsPosts":[{ "id":2, "message":"bar" }] } 

What I would like is to serialize only 1 or possibly 2 levels so that the result is as follows:

  { "Users":[{ "id":1, "newsPosts": [] }], "newsPosts":[{ "id":2, "message":"bar" }] } 

I added:

  json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; 

This is a link removal.

In short: is there a way to set the maximum number of nodes for serialization?

+7
source share
3 answers

Isn't that just a question about how you create data to send from your get function?

I mean, the JSON serializer does its job by serializing all the data you give it, just delete the data or not include it and it will not be serialized.

If this is a more fine-tuning, you are looking for a custom JsonWriter - this is what you want, the link posted by Alex Filipovich gives good information on what to do to achieve this.

0
source

I recommend matching your domain clusters with custom DTO objects using something like AutoMapper and then passing them for serialization.

-one
source

I'm not very familiar with the web API, but it looks like you will want to create your own MediaTypeFormatter that uses the JavaScriptSerializer, which has the property to set the recursion limit.

MSDN - JavaScriptSerializer.RecursionLimit Property

Another option is to create custom formatting using JSON.NET that has the same parameters.

-one
source

All Articles