Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SerializeObject is waiting for ever

Tags:

c#

task

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:

enter image description here

like image 732
Raskolnikov Avatar asked Oct 29 '22 01:10

Raskolnikov


1 Answers

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; }
    } 
}
like image 182
rene Avatar answered Nov 15 '22 05:11

rene