Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop .net JSON serialization from referencing previous elements?

Im using MVC/Web API from MVC 4.5 to serve a JSON service.

All works well until it is required to expose a large JSON result which has certain amounts of repeating data.

For those that arent sure what I mean, if for example I have a list of books, of which each has the full author data, .net will change the 2nd version of the same author to reference the previous one, instead of duplicating the data. In these cases it uses a $X reference, where X is the index of the item to reference.

Whilst I appreciate its an efficiency saving, this format cannot be consumed by our client apps

like image 545
Anthony Main Avatar asked Oct 21 '22 09:10

Anthony Main


1 Answers

The Json.NET has a setting which could do that magic... It is Preserving Object References and here is the link to the documentation:

I would say, that what you are experiencing, is similar to an exmple in the doucmentation

Some extract (but, please, see the docs for more details):

Let's have a collection poeple with two persons. With a small trick: setting PreserveReferencesHandling like this

string json = JsonConvert.SerializeObject(
  people, 
  Formatting.Indented,
  new JsonSerializerSettings 
  { 
     PreserveReferencesHandling = PreserveReferencesHandling.Objects 
  });

We can get result like this:

[
  {
    "$id": "1",
    "Name": "James",
    "BirthDate": "1983-03-08T00:00Z",
    "LastModified": "2012-03-21T05:40Z"
  },
  {
    "$ref": "1"
  }
]

What we can see, is most likely what you do experience. So PreserveReferencesHandling.Objects seems to be the setting of your code. So try to explicitly set it to None like this:

new JsonSerializerSettings 
{ 
    PreserveReferencesHandling = PreserveReferencesHandling.None;
}

And as in the docs:

... By default Json.NET will serialize all objects it encounters by value. If a list contains two Person references, and both references point to the same object then the JsonSerializer will write out all the names and values for each reference...

So this should be the default setting again

Another interesting reading: Serializing Circular References

like image 113
Radim Köhler Avatar answered Oct 27 '22 10:10

Radim Köhler