I have a class structure which has few string properties, and I want to add another property that returns the Json
string value of the very same object dynamically.
My problem is, when I use this
while creating the Json
result, it calls the object again recursively, and crashes with StackOverflowException
at the end.
I tried to change this
field with New Introducer() { Id = this.Id }
but it caused the same error.
Although I am able to solve it by identifying a bool IsSerializing
parameter and bypassing the field for the second time manually, I am looking for a more decent solution.
Is there a command or attribute to prevent compiler from calling Serialized
property for the second time? Or am I calling the property in a wrong way in the first place?
Here is my class:
public class Introducer
{
public Introducer()
{
this.Id = 0;
this.NameSurname = string.Empty;
this.EmailAddress = string.Empty;
this.UserCreated = new User();
}
public int Id { get; set; }
private string _NameSurname;
public string NameSurname { get { return _NameSurname; } set { _NameSurname = value.Trim(); } }
private string _EmailAddress;
public string EmailAddress { get { return _EmailAddress; } set { _EmailAddress = value.Trim(); } }
public DateTime DateCreated { get; set; }
public User UserCreated { get; set; }
public string Serialized
{
get
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
}
Here is a sample to try out. Idea is to use JsonIgnore attribute to instruct the serializer to not pick up the property for serialization.
Invoke as:
EDIT:
Good practice 1: As mentioned in other answers, a
method
could be used instead of theproperty
as below:Good practice 2: Follow the right OOD patterns and let the serialization (or representation) of the object in a format be done in a separate
class
.