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?
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.
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 ).
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.
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.
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...
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