如何排除一些成员被序列化到JSON? [英] How to exclude some members from being serialized to Json?
问题描述
我有我想要序列化到JSON格式的对象 我使用的:
I have an object that I want to serialize to Json format I'm using:
public string ToJson()
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
string sJSON = jsonSerializer.Serialize(this);
return sJSON;
}
在这个不被序列化
如何定义某些领域?
How do I define some fields in "this" to not be serialized ?
感谢
推荐答案
可能的办法是宣布这些领域私人
或内部
。
The possible way is to declare those fields as private
or internal
.
另一种解决方案是使用 DataContractJsonSerializer
类。在这种情况下,您添加 DataContract
属性类。你可以控制你想要数据成员
连载成员属性 - 所有成员都标有它的序列化,和其他人都没有
The alternative solution is to use DataContractJsonSerializer
class. In this case you add DataContract
attribute to your class. You can control the members you want to serialize with DataMember
attribute - all members marked with it are serialized, and the others are not.
您应该重写你的toJSON方法如下:
You should rewrite your ToJson method as follows:
public string ToJson()
{
DataContractJsonSerializer jsonSerializer =
new DataContractJsonSerializer(typeof(<your class name>));
MemoryStream ms = new MemoryStream();
jsonSerializer.WriteObject(ms, this);
string json = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return json;
}
这篇关于如何排除一些成员被序列化到JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!