I have function which serialize objects. It is working fine in every case except when I run with specific object. This is object of class which contains Tasks. But I don't see why would this be problem.
In debug mode code is just stuck without any error, or any exception. Just stop and waiting for ever. Also to mention that this serialization is called in running Task, but also I am not sure why would this be problem.
I have also set attribute [NonSerialized] to all Task properties but still nothing.
[NonSerialized]
private Task<bool> isConnected;
public Task<bool> IsConnected
{
get { return isConnected; }
set { isConnected = value; }
}
This is my function:
public static string ToJson(this object obj)
{
try
{
var res = JsonConvert.SerializeObject(obj, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return res;
}
catch
{
return $"Object {obj.ToString()} is not serializable.";
}
}
This is object I try to serialize:
The NonSerialized
attribute is used by the BinaryFormatter and SoapFormatter but not by the Newtonsoft Json serializer.
So your approach is sound, you only need to annotate your Task
properties with an ignore attribute that is rwad and understood by JsonConvert
.
You have two options.
You can annotate the property with JsonIgnore
that comes with the Newtonsoft assembly. Or you can use the DataContract
and DataMember
attributes found in System.Runtime.Serialization to annotate the members of your class that you want to serialize. In this case your Task<T>
properties would NOT have any attribute.
Here is an example how you use JsonIgnore:
public class Test
{
public Test()
{
isConnected =new Task<bool>(()=> {return true;});
}
public string Foo{get;set;}
private Task<bool> isConnected;
[JsonIgnore] // do not serialize
public Task<bool> IsConnected
{
get { return isConnected; }
set { isConnected = value; }
}
}
And here is the same class when using the DataContract/DataMember option:
[DataContract] // serialize this class
public class Test2
{
public Test2(){
isConnected =new Task<bool>(()=> {return true;});
}
[DataMember] // serialize this property
public string Foo{get;set;}
private Task<bool> isConnected;
// no DataMember so this one isn't serialized
public Task<bool> IsConnected
{
get { return isConnected; }
set { isConnected = value; }
}
}
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