Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize as Json an object structure with circular references?

I have an object structure like this:

public class Proposal {
    public List<ProposalLine> Lines { get; set; }
    public string Title { get; set; }
}

public class ProposalLine {
    public Proposal Proposal { get; set; }  // <- Reference to parent object
}

I try to serialize Proposal as Json, it tells me that there is a circular reference, which is correct.
Unfortunately, I can't touch the objects, since they are in a referenced DLL from another project - otherwise I'd change them.

Is there a way to serialize as Json and ignore the circular properties?

like image 939
AngryHacker Avatar asked Jul 23 '13 18:07

AngryHacker


People also ask

How do you serialize a JSON object?

NET objects as JSON (serialize) To write JSON to a string or to a file, call the JsonSerializer. Serialize method. The JSON output is minified (whitespace, indentation, and new-line characters are removed) by default.

How do you preserve references and handle or ignore circular references in system text JSON?

To preserve references and handle circular references, set ReferenceHandler to Preserve. This setting causes the following behavior: On serialize: When writing complex types, the serializer also writes metadata properties ( $id , $values , and $ref ).

What is circular JSON?

The circular structure you have is not in JSON, but in the object that you are trying to convert to JSON. Circular structures come from objects which contain something which references the original object. JSON does not have a manner to represent these.

What is the difference between JSON and serialization?

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). If you serialize this result it will generate a text with the structure and the record returned.


1 Answers

Use the Newtonsoft.Json (which is the default .net json serializer) and set

JsonSerializerSettings settings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
var serializer = JsonSerializer.Create(settings);

You can also globally define this variable if you are developing MVC applications...

like image 99
MichaC Avatar answered Oct 07 '22 15:10

MichaC