I have a test class which I am trying to serialize:
public class Testing
{
private string _name;
private string _firstname = "firstname";
public string _lastname;
private DateTime _datenow = DateTime.Now;
public DateTime _birthdate = DateTime.Now;
public string Name { get { return _name; } set { _name = value; } }
}
I am using a custom JsonConverter
to handle the serialization for the test class:
public class TestingConverter : JsonConverter
{
private Type[] _types = new Type[] { typeof(Testing)};
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
try
{
JToken t = JToken.FromObject(value); //This is what i want to do
//rest of code
}
catch (Exception ex)
{
Console.Write(ex.Message);
throw;
}
}
public override bool CanRead
{
get
{
return false;
}
}
}
If I perform the serialization by passing the converter to the JsonSerializer
object it works fine:
Testing t = new Testing();
t._lastname = "USER LAST NAME";
JsonSerializer p = JsonSerializer.CreateDefault();
p.Converters.Add(new TestingConverter());
using (StreamWriter file = File.CreateText("output.json"))
using (JsonTextWriter writer = new JsonTextWriter(file))
{
p.Serialize(writer, t);
}
But, if I instead mark my test class with a [JsonConverter]
attribute:
[JsonConverter(typeof(TestingConverter))]
public class Testing
{
private string _name;
private string _firstname = "firstname";
public string _lastname;
private DateTime _datenow = DateTime.Now;
public DateTime _birthdate = DateTime.Now;
public string Name { get { return _name; } set { _name = value; } }
}
and serialize like this:
Testing t = new Testing();
t._lastname = "USER LAST NAME";
JsonSerializer p = JsonSerializer.CreateDefault();
using (StreamWriter file = File.CreateText("output.json"))
using (JsonTextWriter writer = new JsonTextWriter(file))
{
p.Serialize(writer, t);
}
my TestingConverter
class is called, but it goes into a recursive loop at the JToken.FromObject(value)
method and finally crashes with a StackOverflowException
.
Can anyone tell me why this is happening? What am I missing?