如果我尝试使用System.Runtime.Serialization.Json.DataContractJsonSerializer序列化以下ClassToSerialize类的对象
[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());
}
返回字符串仍包含IsMf属性及其值。 NOnSerialized属性被忽略。有人可以建议在使用DataContractJsonSerializer时使用什么属性,以便不序列化某些属性
答案 0 :(得分:4)
以下代码对我有用(它几乎与您的代码相同,并修复了一些小的编译错误):
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; }
}
<强>输出:强>
{"NoResults":true,"PrimaryExc":"a"}
答案 1 :(得分:2)
不,它不包含它。你一定是弄错了:
[DataContract]
public class ClassToSerialize
{
[NonSerialized]
private bool _mf;
public bool IsMf
{
get { return _mf; }
set{ _mf = value;}
}
[DataMember]
public char PrimaryExc { get; set; }
}
class Program
{
static void Main()
{
var obj = new ClassToSerialize
{
PrimaryExc = 'a',
IsMf = false
};
var serializer = new DataContractJsonSerializer(obj.GetType());
serializer.WriteObject(Console.OpenStandardOutput(), obj);
}
}
输出:
{"PrimaryExc":"a"}
备注:您的班级不需要[Serializable]
属性。这仅适用于binary serialization。