System.Runtime.Serialization.Json.DataContractJsonSerializer.WriteObject ignores NonSerialized attribute while serializing

labroo picture labroo · Nov 20, 2010 · Viewed 16.2k times · Source

If i try to serialize an object of the following ClassToSerialize class with System.Runtime.Serialization.Json.DataContractJsonSerializer

[DataContract,Serializable]
public class ClassToSerialize
{
    [NonSerialized] private bool _mf;
    public bool IsMf
    { 
        get { return _mf};
        set{ _mf = value;} 
    }

    [DataMember]
    public char PrimaryExc { get; set; }        
}

public class TestClass
{
    ClassToSerialize obj = new ClassToSerialize{PrimaryExchange = 'a', NoResults = true};
    var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(ClassToSerialize);
    var ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    return Encoding.UTF8.GetString(ms.ToArray());
}

The return string still contains IsMf property and its value. The NOnSerialized attribute is ignored. Can someone please suggest what attribute to use when using DataContractJsonSerializer so as to not serialize some properties

Answer

Andrew Hare picture Andrew Hare · Nov 20, 2010

The following code worked for me (it's almost identical to your's with a few small compilation errors fixed):

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

class Program
{
    static void Main()
    {
        var obj = new ClassToSerialize
        {
            PrimaryExc = 'a', 
            NoResults = true
        };

        var serializer 
            = new DataContractJsonSerializer(typeof(ClassToSerialize));

        var ms = new MemoryStream();

        serializer.WriteObject(ms, obj);

        Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
    }
}

[DataContract]
[Serializable]
public class ClassToSerialize
{
    [NonSerialized]
    private bool _mf;

    public bool IsMf
    {
        get { return _mf; }
        set { _mf = value; }
    }

    [DataMember]
    public bool NoResults { get; set; }

    [DataMember]
    public char PrimaryExc { get; set; }
}

Output:

{"NoResults":true,"PrimaryExc":"a"}